-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.go
86 lines (70 loc) · 1.6 KB
/
server.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
package etp
import (
"fmt"
"net/http"
"github.com/coder/websocket"
"github.com/txix-open/etp/v4/internal"
)
type Server struct {
idGenerator *internal.IdGenerator
mux *mux
rooms *Rooms
opts *serverOptions
}
func NewServer(opts ...ServerOption) *Server {
options := defaultServerOptions()
for _, opt := range opts {
opt(options)
}
return &Server{
idGenerator: internal.NewIdGenerator(),
mux: newMux(),
rooms: newRooms(),
opts: options,
}
}
func (s *Server) On(event string, handler Handler) *Server {
s.mux.On(event, handler)
return s
}
func (s *Server) OnConnect(handler ConnectHandler) *Server {
s.mux.OnConnect(handler)
return s
}
func (s *Server) OnDisconnect(handler DisconnectHandler) *Server {
s.mux.OnDisconnect(handler)
return s
}
func (s *Server) OnError(handler ErrorHandler) *Server {
s.mux.OnError(handler)
return s
}
func (s *Server) OnUnknownEvent(handler Handler) *Server {
s.mux.OnUnknownEvent(handler)
return s
}
func (s *Server) Rooms() *Rooms {
return s.rooms
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ws, err := websocket.Accept(w, r, s.opts.acceptOptions)
if err != nil {
s.mux.handleError(nil, fmt.Errorf("websocket accept error: %w", err))
return
}
defer func() {
_ = ws.CloseNow()
}()
ws.SetReadLimit(s.opts.readLimit)
id := s.idGenerator.Next()
conn := newConn(id, r, ws)
s.rooms.add(conn)
defer s.rooms.remove(conn)
keeper := newKeeper(conn, s.mux)
keeper.Serve(r.Context())
}
func (s *Server) Shutdown() {
for _, conn := range s.rooms.AllConns() {
_ = conn.Close()
}
}