Server pushes updates to the client over a single HTTP connection
- Set up the HTTP server:
http.ListenAndServe(":8000", nil)
- Write the HTTP handler to send events:
We send current timestamps, wrapped infmt.Fprintf
and flush the data.
SSEHandler(w http.ResponseWriter, r *http.Request)
for {
fmt.Fprintf(w, "data: Current time is %s\n\n", time.Now().Format(time.RFC3339))
// flush the data to the client - immideately, not buffer
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
}
- Set up the client to listen to the events:
const eventSource = new EventSource("http://localhost:8080/events");
// Listen for messages from the server
eventSource.onmessage = function(event) {
const newElement = document.createElement("div");
newElement.textContent = event.data;
document.getElementById("events").appendChild(newElement);
};