How do I stream responses with Echo in Go?

In this example, we'll see how to stream responses using the Echo web framework in Go. Streaming responses allows the server to send data to the client as it becomes available, rather than waiting for all the data to be ready before sending it.

Streaming, Echo, Go, Web Framework, HTTP Response, Real-time Data
This guide demonstrates how to efficiently stream responses in Echo, a popular web framework in Go, enabling real-time data handling for web applications.

package main

import (
    "net/http"
    "time"

    "github.com/labstack/echo/v4"
)

func streamResponse(c echo.Context) error {
    // Set the HTTP headers for chunked transfer encoding
    c.Response().Header().Set(echo.HeaderContentType, "text/event-stream")
    c.Response().WriteHeader(http.StatusOK)

    // Stream data
    for i := 0; i < 10; i++ {
        // Send the data
        if _, err := c.Response().Write([]byte("data: Chunk " + strconv.Itoa(i) + "\n\n")); err != nil {
            return err
        }
        c.Response().Flush() // Flush the data to the client

        time.Sleep(time.Second) // Simulate delay
    }

    return nil
}

func main() {
    e := echo.New()

    e.GET("/stream", streamResponse)

    e.Start(":8080")
}
    

Streaming Echo Go Web Framework HTTP Response Real-time Data