-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsse.go
75 lines (67 loc) · 1.26 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
package sse
import (
"fmt"
"github.com/google/uuid"
"log"
"net/http"
"sync"
)
type Server struct {
mu sync.RWMutex
chans map[uuid.UUID]chan message
}
func New() *Server {
return &Server{
chans: make(map[uuid.UUID]chan message),
}
}
func (s *Server) HandlerFunc(w http.ResponseWriter, r *http.Request) {
chanId := uuid.New()
c := make(chan message)
s.mu.Lock()
s.chans[chanId] = c
s.mu.Unlock()
defer func() {
s.mu.Lock()
delete(s.chans, chanId)
close(c)
s.mu.Unlock()
}()
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
flusher, ok := w.(http.Flusher)
if !ok {
log.Println("ResponseWriter does not implement http.Flusher")
return
}
flusher.Flush()
for {
select {
case <-r.Context().Done():
fmt.Println("SSE " + chanId.String() + " closed")
return
case m := <-c:
if err := m.writeTo(w); err != nil {
log.Println("Unable to write")
return
}
if _, err := w.Write([]byte("\n")); err != nil {
log.Println("Unable to write")
return
}
flusher.Flush()
}
}
}
func (s *Server) Send(id int, event string, data []byte) {
s.mu.RLock()
defer s.mu.RUnlock()
m := message{
id: id,
event: event,
data: data,
}
for _, c := range s.chans {
c <- m
}
}