This repository has been archived by the owner on Oct 25, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
subscribe.go
64 lines (52 loc) · 1.64 KB
/
subscribe.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
package main
import (
"fmt"
"net/http"
"time"
"github.com/julienschmidt/httprouter"
)
func (h *Handler) SubscribeContact(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
Subscribe(h.contactConnections, w, r, p)
}
func (h *Handler) SubscribeConversation(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
Subscribe(h.conversationConnections, w, r, p)
}
func (h *Handler) SubscribeUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
Subscribe(h.userConnections, w, r, p)
}
func (h *Handler) SubscribeMember(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
conversation := p.ByName("conversation")
if _, ok := h.memberConnections[conversation]; !ok {
h.memberConnections[conversation] = make(map[string]chan []byte)
}
Subscribe(h.memberConnections[conversation], w, r, p)
}
func Subscribe(channels map[string]chan []byte, w http.ResponseWriter, r *http.Request, p httprouter.Params) {
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
id := RandomHex()
recv := make(chan []byte)
channels[id] = recv
// Refresh connection periodically
resClosed := w.(http.CloseNotifier).CloseNotify()
ticker := time.NewTicker(25 * time.Second)
for {
select {
case msg := <-recv:
fmt.Fprintf(w, "data: %s\n\n", msg)
flusher.Flush()
case <-ticker.C:
w.Write([]byte(":\n\n"))
case <-resClosed:
ticker.Stop()
delete(channels, id)
return
}
}
}