-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
52 lines (43 loc) · 1.26 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
package ws
import (
"github.com/gorilla/websocket"
"net/http"
)
type (
EndpointHandler func(r *http.Request, accept func(endpointId string) IEndpoint, reject func(httpStatus int))
CloseHandler func(endpointId string, code int, text string)
)
func NewServer(option Option) Server {
return &ServerImpl{
option: parseOption(option),
upgrade: &websocket.Upgrader{
ReadBufferSize: option.ReadBufferSize,
WriteBufferSize: option.WriteBufferSize,
HandshakeTimeout: option.HandshakeTimeout,
CheckOrigin: func(r *http.Request) bool {
return true
},
},
}
}
type Server interface {
UpgradeEndpoint(endpointId string, w http.ResponseWriter, r *http.Request) (IEndpoint, error)
}
type ServerImpl struct {
option Option
upgrade *websocket.Upgrader
endpointHandler EndpointHandler
}
func (s *ServerImpl) UpgradeEndpoint(endpointId string, w http.ResponseWriter, r *http.Request) (IEndpoint, error) {
responseHeader := http.Header{
"Sec-WebSocket-Protocol": r.Header.Values("Sec-WebSocket-Protocol"),
}
conn, err := s.upgrade.Upgrade(w, r, responseHeader)
if err != nil {
return nil, err
}
return NewEndpoint(endpointId, conn), nil
}
func (s *ServerImpl) EndpointHandler(handler EndpointHandler) {
s.endpointHandler = handler
}