-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket.go
86 lines (76 loc) · 1.57 KB
/
websocket.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 bingx
import (
"net/http"
"github.com/gorilla/websocket"
"github.com/magicaleks/go-bingx/common"
)
// WsHandler handle raw websocket message
type WsHandler func([]byte)
// ErrHandler handles errors
type ErrHandler func(err error)
// WsConfig webservice configuration
type WsConfig struct {
Endpoint string
}
func newWsConfig(endpoint string) *WsConfig {
return &WsConfig{
Endpoint: endpoint,
}
}
var wsServe = func(initMessage []byte, config *WsConfig, handler WsHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
header := http.Header{}
header.Add("Accept-Encoding", "gzip")
c, _, err := websocket.DefaultDialer.Dial(config.Endpoint, header)
if err != nil {
return nil, nil, err
}
if initMessage != nil {
err = c.WriteMessage(websocket.TextMessage, initMessage)
if err != nil {
return nil, nil, err
}
}
c.SetReadLimit(655350)
doneC = make(chan struct{})
stopC = make(chan struct{})
go func() {
defer close(doneC)
silent := false
go func() {
select {
case <-stopC:
silent = true
case <-doneC:
}
c.Close()
}()
for {
_, message, err := c.ReadMessage()
if err != nil {
if !silent {
errHandler(err)
}
return
}
decodedMsg, err := common.DecodeGzip(message)
if err != nil {
if !silent {
errHandler(err)
}
return
}
if string(decodedMsg) == "Ping" {
err = c.WriteMessage(websocket.TextMessage, []byte("Pong"))
if err != nil {
if !silent {
errHandler(err)
}
return
}
continue
}
handler(decodedMsg)
}
}()
return
}