Learning Server Side Events
You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Drew Bednar fcceaa9b81 Working example 10 months ago
ui Working example 10 months ago
.air.toml Working example 10 months ago
.gitignore Working example 10 months ago
LICENSE Initial commit 10 months ago
README.md Adding TODO and additional notes in README to correct mdn documentation 10 months ago
go.mod Working example 10 months ago
main.go Working example 10 months ago

README.md

learning_sse

Learning Server Side Events can be fun.

The magic is in setting the Content Type header to text/event-stream, writing the response in the from of data: %s \n\n, and flushing the content of the WriteResponse buffer manually. This is necessary because by default Go will implicitly flush the buffer only once the Handler has returned.

func SSEHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/event-stream")

	tokens := strings.Split("Hey there Drew. I hope you enjoy The Alters!", " ")
	for _, token := range tokens {
		w.Write([]byte(fmt.Sprintf("data: %s \n\n", token)))
		w.(http.Flusher).Flush()
		time.Sleep(time.Millisecond * 420)
	}
}

Use go run main.go and try curling the the sse endpoint.

curl http://0.0.0.0:8888/sse