-
Notifications
You must be signed in to change notification settings - Fork 7
/
websocket.go
107 lines (87 loc) · 2.29 KB
/
websocket.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
package main
import (
"net/http"
"time"
"github.com/go-chi/chi/v5"
"github.com/gorilla/websocket"
)
const (
pingPeriod = 50 * time.Second
inactiveTimeout = 2 * time.Minute
writeTimeout = 5 * time.Second
)
var upgrader = websocket.Upgrader{}
func handleSocket(w http.ResponseWriter, r *http.Request) {
topic := chi.URLParam(r, "topic")
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
writeError(w, r, http.StatusUpgradeRequired, err)
return
}
wss := &wsSub{sendC: make(chan []byte, 20)}
sub(topic, wss)
go wss.handle(conn, topic)
}
type wsSub struct {
sendC chan []byte
}
func (wss *wsSub) Send(data []byte) { wss.sendC <- data }
// handle manages the lifecycle of a websocket connection and ensures the subscriber is unsubscribed on closure.
func (wss *wsSub) handle(conn *websocket.Conn, topic string) {
defer conn.Close()
defer unsub(topic, wss)
// this channel is used to signal read operations success
// receiving a nil error resets the inactivity timer
// receiving an error closes the connection
readerr := make(chan error, 10)
// start reading from the connection, this is required to read pongs
// and to detect connection closure
go func() {
for {
_, _, err := conn.ReadMessage()
readerr <- err
if err != nil {
return
}
}
}()
// receiving a ping resets the inactivity timeout
conn.SetPongHandler(func(string) error {
readerr <- nil
return nil
})
pingt := time.NewTicker(pingPeriod)
timeout := time.NewTicker(inactiveTimeout)
for {
select {
// send published data
case data := <-wss.sendC:
if err := wsWrite(conn, websocket.TextMessage, data); err != nil {
return
}
// check for read error
// reset timers on nil, error
case rerr := <-readerr:
if rerr != nil {
return
}
pingt.Reset(pingPeriod)
timeout.Reset(inactiveTimeout)
// send a ping, reset inactivity timer
case <-pingt.C:
if err := wsWrite(conn, websocket.PingMessage, nil); err != nil {
return
}
// abort on timeout
case <-timeout.C:
return
}
}
}
// wsWrite writes a message to the websocket connection with a deadline
func wsWrite(conn *websocket.Conn, mtype int, data []byte) error {
if err := conn.SetWriteDeadline(time.Now().Add(writeTimeout)); err != nil {
return err
}
return conn.WriteMessage(mtype, data)
}