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)
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?