How do I stream SSE (Server-Sent Events)?

To stream Server-Sent Events (SSE) in Go, you need to set up an HTTP handler that sends event data to the client using the correct content type and encoding. Below is a simple example that demonstrates how to implement SSE in Go.

package main import ( "fmt" "net/http" "time" ) func sseHandler(w http.ResponseWriter, r *http.Request) { // Set headers for SSE w.Header().Set("Content-Type", "text/event-stream") w.Header().Set("Cache-Control", "no-cache") w.Header().Set("Connection", "keep-alive") // Senddata every second for { // Create event message fmt.Fprintf(w, "data: Current Time: %s\n\n", time.Now().String()) // Flush the response to the client if flusher, ok := w.(http.Flusher); ok { flusher.Flush() } // Sleep for 1 second time.Sleep(1 * time.Second) } } func main() { http.HandleFunc("/events", sseHandler) http.ListenAndServe(":8080", nil) }

Keywords: Go Server-Sent Events SSE HTTP Streaming Real-time Updates