-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
reload.go
111 lines (83 loc) · 2.1 KB
/
reload.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package serve
import (
"log"
"strings"
"sync"
"sync/atomic"
"time"
"golang.org/x/net/websocket"
)
var reloadC = make(chan struct{}, 1)
type wsc struct {
ws *websocket.Conn
closeC chan struct{}
}
// keep all connections in map for broadcast
var connections = map[wsc]bool{}
// lock for ^^
var connMU sync.Mutex
// count of loaded to come back
var numReloading int32
// wshandler handles the numReloading when serve -L is used
func WebsocketHandler(ws *websocket.Conn) {
// add new conn and chan to close
cc := wsc{ws: ws, closeC: make(chan struct{}, 1)}
connMU.Lock()
// inc new conn
atomic.AddInt32(&numReloading, 1)
connections[cc] = true
connMU.Unlock()
pinger := time.NewTicker(time.Second * 5)
defer func() {
pinger.Stop()
ws.Close()
}()
// just read once...
go func() {
var msg string
ws.SetReadDeadline(time.Now().Add(time.Second * 5))
err := websocket.Message.Receive(ws, &msg)
if err != nil {
log.Println(err, "error in receive")
}
}()
for {
select {
// close and decrement count
case <-cc.closeC:
cc.closeC = nil
return
case <-pinger.C:
ws.SetWriteDeadline(time.Now().Add(time.Second * 10))
// presume no news is good news. err/news == closed i.e refresh/tab/browser closed
if err := websocket.Message.Send(ws, "ping"); err != nil {
connMU.Lock()
delete(connections, cc)
connMU.Unlock()
return
}
case <-reloadC:
connMU.Lock()
// broadcast to all
for wlst := range connections {
// not sure how important this is for way we use
wlst.ws.SetWriteDeadline(time.Now().Add(time.Second * 10))
err := websocket.Message.Send(wlst.ws, "reload")
// todo: check error and log somewhere
_ = err
}
// empty all conns and close
for k := range connections {
// close each conn individually. Should catch edge cases where closing tabs/browsers even while reloading..
k.closeC <- struct{}{}
delete(connections, k)
}
connMU.Unlock()
return
}
}
}
// debugging
func paddr(ws *websocket.Conn) string {
return ws.Request().RemoteAddr[strings.LastIndex(ws.Request().RemoteAddr, ":")+1:]
}