Hi! I just implemented this tutorial for sse on go: https://www.kelche.co/blog/go/server-sent-events/. When event comes my client just write it in the console. it works but sometimes i see errors and idk what was the cause (see screenshot).
PS: i use tls connection, but all certs is valid
the code:
server side
func (s *Service) SSE(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Content-Type", "text/event-stream")
// send a random number every 2 seconds
for {
rand.Seed(time.Now().UnixNano())
fmt.Fprintf(w, "data: %d \n\n", rand.Intn(100))
w.(http.Flusher).Flush()
time.Sleep(2 * time.Second)
}
}
client
const onLoaded = () => {
let eventSource = new EventSource("/events");
eventSource.onmessage = function(event) {
console.log(`New event:`, event.data);
};
}
https://www.kelche.co/blog/go/server-sent-events/
Learn how to implement Server-Sent Events (SSE) in Golang with our comprehensive guide. Stream real-time updates to clients without any complexity!