-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
63 lines (50 loc) · 1.45 KB
/
server.go
File metadata and controls
63 lines (50 loc) · 1.45 KB
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
package websocket
import (
"net/http"
"github.com/gorilla/websocket"
"github.com/sirupsen/logrus"
)
type WebSocketServer struct {
log *logrus.Entry
upgrader websocket.Upgrader
subprotocols map[string]*Subprotocol
}
func NewWebSocketServer() *WebSocketServer {
return &WebSocketServer{
log: logrus.NewEntry(logrus.New()),
upgrader: websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
EnableCompression: true,
Subprotocols: []string{},
},
subprotocols: map[string]*Subprotocol{},
}
}
func (ws *WebSocketServer) SetLogger(logger *logrus.Entry) {
ws.log = logger
}
func (ws *WebSocketServer) Subprotocol(name string) (subp *Subprotocol) {
if _, ok := ws.subprotocols[name]; ok {
panic("WebSocketServer: Duplicate Subprotocol")
}
subp = newSubProtocol(name)
ws.subprotocols[name] = subp
ws.upgrader.Subprotocols = append(ws.upgrader.Subprotocols, name)
return
}
// ServeHTTP implements the http.Handler interface
func (ws *WebSocketServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
conn, err := ws.upgrader.Upgrade(w, r, nil)
if err != nil {
ws.log.WithError(err).Error("Connection upgrade failed")
return
}
// REVIEW: What happens if client specifies no subprotocols
// use a default subprotocol to handle those cases
subp := ws.subprotocols[conn.Subprotocol()]
socket := NewSocket(conn, subp, ws.log)
go socket.writePump()
go socket.readPump()
subp.newConnection(r, socket)
}