Skip to content

Instantly share code, notes, and snippets.

@marconi
Created March 15, 2016 12:10
Show Gist options
  • Save marconi/97ee165b258a32b7874c to your computer and use it in GitHub Desktop.
Save marconi/97ee165b258a32b7874c to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"log"
"net/http"
"strings"
"time"
)
var (
datacounter = 0
newline = "\n"
)
func main() {
http.HandleFunc("/events", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Transfer-Encoding", "chunked")
for e := range time.Tick(2 * time.Second) {
datacounter += 1
fmt.Fprint(w, formatData(datacounter, "time", e.String()))
w.(http.Flusher).Flush()
}
})
log.Fatal(http.ListenAndServe("127.0.0.1:8080", nil))
}
func formatData(id int, event, data string) string {
var output []string
if id > 0 {
output = append(output, fmt.Sprintf("id: %d", id))
}
if event != "" {
output = append(output, fmt.Sprintf("event: %s", event))
}
datas := strings.Split(data, newline)
for i, data := range datas {
datas[i] = fmt.Sprintf("data: %s", data)
}
output = append(output, strings.Join(datas, newline))
return strings.Join(output, newline) + strings.Repeat(newline, 2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment