/
sse.go
82 lines (64 loc) · 1.53 KB
/
sse.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package sse
import (
"fmt"
"net/http"
)
type Broker struct {
Notifier chan []byte
clients map[chan []byte]bool
closingClients chan chan []byte
newClients chan chan []byte
}
func NewBrokerServer() (broker *Broker) {
broker = &Broker{
// Make notifier a buffered(asynchronous) channel
Notifier: make(chan []byte, 1),
clients: make(map[chan []byte]bool),
closingClients: make(chan chan []byte),
newClients: make(chan chan []byte),
}
go broker.Listen()
return
}
func (b *Broker) Listen() {
for {
select {
case newClient := <-b.newClients:
b.clients[newClient] = true
case closedClient := <-b.closingClients:
delete(b.clients, closedClient)
case event := <-b.Notifier:
for client, _ := range b.clients {
client <- event
}
}
}
}
func (b *Broker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming unsupported", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Access-Control-Allow-Origin", "*")
messageChannel := make(chan []byte)
b.newClients <- messageChannel
defer func() {
b.closingClients <- messageChannel
}()
notify := w.(http.CloseNotifier).CloseNotify()
for {
select {
case <-notify:
return
default:
data := <-messageChannel
// SSE data formatting
fmt.Fprintf(w, "data: %s\n\n", data)
flusher.Flush()
}
}
}