-
Notifications
You must be signed in to change notification settings - Fork 0
/
ws.go
65 lines (54 loc) · 1.17 KB
/
ws.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
package sona
import (
"context"
"github.com/gobwas/ws"
"github.com/gobwas/ws/wsutil"
"github.com/snowmerak/sona/lib/listmap"
"net/http"
)
func (s *Sona) EnableWS(ctx context.Context, addr string) *Sona {
s.wsServer = new(http.Server)
s.wsServer.Addr = addr
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if s.onConnect != nil {
s.onConnect(w, r)
}
defer func() {
if s.onDisconnect != nil {
s.onDisconnect(w, r)
}
}()
conn, _, _, err := ws.UpgradeHTTP(r, w)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
path := r.URL.Path
name := r.RemoteAddr
errorOccurred := make(chan struct{}, 1)
value, _ := s.connMap.GetOrInsert(path, listmap.New())
value.Append(name, func(data []byte) {
defer func() {
_ = recover()
}()
if s.onSend != nil {
s.onSend(w, r)
}
if err := wsutil.WriteServerBinary(conn, data); err != nil {
errorOccurred <- struct{}{}
close(errorOccurred)
return
}
})
defer value.Remove(name)
done := ctx.Done()
select {
case <-done:
case <-errorOccurred:
}
_ = conn.Close()
})
s.wsServer.Handler = mux
return s
}