-
Notifications
You must be signed in to change notification settings - Fork 0
/
api_base.go
53 lines (41 loc) · 1.08 KB
/
api_base.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
package msg2api
import (
"errors"
"github.com/gorilla/websocket"
"net/http"
"time"
)
const (
upgradeTimeout = 10 * time.Second
deviceAPIProtocolV1 = "v2.device.msg"
userAPIProtocolV3 = "v5.user.msg"
)
var errProtocolNegotiationFailed = errors.New("protocol negotiation failed")
type apiBase struct {
socket *socketWrapper
}
func (b *apiBase) Close() {
b.socket.Close(websocket.CloseGoingAway, "")
}
func initAPIBaseFromSocket(conn *websocket.Conn) (*apiBase, error) {
if conn.Subprotocol() == "" {
conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseProtocolError, ""))
conn.Close()
return nil, errProtocolNegotiationFailed
}
conn.SetReadLimit(4096)
return &apiBase{
socket: wrapWebsocket(conn),
}, nil
}
func initAPIBaseFromHTTP(w http.ResponseWriter, r *http.Request, protocols []string) (*apiBase, error) {
upgrader := websocket.Upgrader{
HandshakeTimeout: upgradeTimeout,
Subprotocols: protocols,
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return nil, err
}
return initAPIBaseFromSocket(conn)
}