-
Notifications
You must be signed in to change notification settings - Fork 1
/
http.go
48 lines (45 loc) · 1.05 KB
/
http.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package main
import (
"fmt"
"log"
"net/http"
)
func blunderServer(w http.ResponseWriter, req *http.Request) {
h := w.Header()
h.Set("Content-Type", "text/event-stream")
h.Set("Transfer-Encoding", "chunked")
h.Set("Cache-Control", "no-cache")
h.Set("Connection", "keep-alive")
h.Set("X-Accel-Buffering", "no") // For Nginx
w.WriteHeader(200)
channel := Subscribe()
defer func() {
log.Println("Closing http connection closes is channel.")
/*FIMXE finding how to close channel when curl make a ctrl-C*/
channel.Leave()
}()
f, f_ok := w.(http.Flusher)
log.Println(f_ok)
if f_ok {
f.Flush()
}
for {
m := <-channel.channel
msg := fmt.Sprintf("data: %s\n\n", m) // message brings its own \n
w.Write([]byte(msg))
if f_ok {
f.Flush()
}
log.Println("One event")
log.Println(msg)
}
}
func startHttp() {
http.HandleFunc("/blunder", blunderServer)
http.Handle("/", http.FileServer(http.Dir("static")))
log.Printf("About to start http://localhost:8000")
err := http.ListenAndServe("localhost:8000", nil)
if err != nil {
panic(err)
}
}