/
server.go
83 lines (68 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
package wss
import (
"net/http"
"github.com/gorilla/websocket"
)
// Conn is an middleman between the websocket connection and the hub.
type Conn struct {
// The websocket connection.
ws *websocket.Conn
// Selected request headers
headers map[string]string
// Connection subscriptions
subscriptions map[string]bool
// Buffered channel of outbound messages.
send chan []byte
}
// Config Server config
type Config struct {
}
// Server Websocket server
type Server struct {
hub *hub
Conf *Config
routers routerMap
upgrader *websocket.Upgrader
}
type routerMap map[string]IRouter
// NewServer make a new websocket server
func NewServer(conf *Config) *Server {
return &Server{
hub: newHub(),
Conf: conf,
routers: make(routerMap),
upgrader: &websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
Subprotocols: []string{"actioncable-v1-json"},
ReadBufferSize: 1024,
WriteBufferSize: 1024,
},
}
}
// ServeWS handles websocket requests from the peer.
func (s *Server) ServeWS(w http.ResponseWriter, r *http.Request) {
ws, err := s.upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
client := newClient(s, ws, r.Header.Get("X-Request-ID"))
client.run()
}
// Start start server
func (s *Server) Start() {
go s.hub.run()
for _, r := range s.routers {
go r.Run()
}
}
// Stop stop server
func (s *Server) Stop() {
for _, r := range s.routers {
r.Stop()
}
s.hub.stop()
}
// RegisterRouter register a router which implement IRouter interface
func (s *Server) RegisterRouter(router IRouter) {
s.routers[router.Channel()] = router
}