Created
May 30, 2014 21:08
-
-
Save cee-dub/883789dc11c82ae5d05f to your computer and use it in GitHub Desktop.
Simple Golang SSE example using CloseNotifier
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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