-
Notifications
You must be signed in to change notification settings - Fork 1
/
sse_handler.go
46 lines (40 loc) · 962 Bytes
/
sse_handler.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
package dev
import (
"fmt"
"net/http"
"time"
)
func sseHandler(manager *ClientManager) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
msg := make(chan RefreshFilePayload, 1)
client := &Client{id: r.RemoteAddr, notify: msg}
manager.register <- client
defer func() {
manager.unregister <- client
}()
go func() {
<-r.Context().Done()
manager.unregister <- client
}()
for {
select {
case m := <-msg:
// encode as json
json := fmt.Sprintf(
`{"changeType": "%s", "criticalCss": "%s", "normalCssUrl": "%s", "at": "%s"}`,
m.ChangeType,
m.CriticalCSS,
m.NormalCSSURL,
m.At.Format(time.RFC3339),
)
fmt.Fprintf(w, "data: %s\n\n", json)
w.(http.Flusher).Flush()
case <-r.Context().Done():
return
}
}
}
}