How to Implement Server-Sent Events (SSE) in Go

Web
Implement SSE in Go by setting the text/event-stream header and flushing data to the response writer.

Implement Server-Sent Events (SSE) in Go by setting the Content-Type header to text/event-stream and writing data directly to the http.ResponseWriter.

func sseHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-cache")
	w.Header().Set("Connection", "keep-alive")
	w.Header().Set("Access-Control-Allow-Origin", "*")

	for i := 0; i < 5; i++ {
		fmt.Fprintf(w, "data: %s\n\n", "Hello from Go SSE")
		w.(http.Flusher).Flush()
		time.Sleep(2 * time.Second)
	}
}