How do I stream responses with Chi in Go?

To stream responses with the Chi router in Go, you can write to the response writer in chunks. Here is a simple example demonstrating this functionality:


    package main

    import (
        "net/http"
        "github.com/go-chi/chi/v5"
        "time"
    )

    func main() {
        r := chi.NewRouter()

        r.Get("/stream", func(w http.ResponseWriter, r *http.Request) {
            w.Header().Set("Content-Type", "text/event-stream")
            w.Header().Set("Cache-Control", "no-cache")
            w.WriteHeader(http.StatusOK)

            for i := 0; i < 10; i++ {
                // Write chunked response
                _, err := w.Write([]byte("data: Hello, World!\n\n"))
                if err != nil {
                    return
                }
                // Flush the data to the client
                if fl, ok := w.(http.Flusher); ok {
                    fl.Flush()
                }
                // Sleep for a second before sending the next chunk
                time.Sleep(1 * time.Second)
            }
        })

        http.ListenAndServe(":8080", r)
    }
    

Go Chi HTTP Streaming Real-time Applications Golang