Skip to content

Instantly share code, notes, and snippets.

@cee-dub
Created May 30, 2014 21:08
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cee-dub/883789dc11c82ae5d05f to your computer and use it in GitHub Desktop.
Save cee-dub/883789dc11c82ae5d05f to your computer and use it in GitHub Desktop.
Simple Golang SSE example using CloseNotifier
package main
import (
"fmt"
"log"
"net/http"
"time"
)
// SSE writes Server-Sent Events to an HTTP client.
type SSE struct{}
var messages = make(chan string)
func (s *SSE) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
f, ok := rw.(http.Flusher)
if !ok {
http.Error(rw, "cannot stream", http.StatusInternalServerError)
return
}
rw.Header().Set("Content-Type", "text/event-stream")
rw.Header().Set("Cache-Control", "no-cache")
rw.Header().Set("Connection", "keep-alive")
cn, ok := rw.(http.CloseNotifier)
if !ok {
http.Error(rw, "cannot stream", http.StatusInternalServerError)
return
}
for {
select {
case <-cn.CloseNotify():
log.Println("done: closed connection")
return
case msg := <-messages:
fmt.Fprintf(rw, "data: %s\n\n", msg)
f.Flush()
}
}
}
func main() {
http.Handle("/", &SSE{})
go func() {
for i := 0; i < 10; i++ {
messages <- "yo"
time.Sleep(time.Second)
}
}()
log.Fatal(http.ListenAndServe(":3000", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment