-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
wsclient.go
62 lines (48 loc) · 1.26 KB
/
wsclient.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
package lanyard
import (
"log"
"strings"
"time"
"github.com/sacOO7/gowebsocket"
)
const (
PING_PERIOD = 30 * time.Second
)
type WSClient struct {
socket gowebsocket.Socket
ticker *time.Ticker
}
func (client WSClient) Destroy() {
if client.ticker != nil {
client.ticker.Stop()
}
client.socket.Close()
}
func (client WSClient) ping() {
client.ticker = time.NewTicker(PING_PERIOD)
defer client.ticker.Stop()
for ; ; <-client.ticker.C {
client.socket.SendText("{\"op\":3}")
}
}
func clientFactory(subscription string, subscription_data string, onMessage func(client WSClient, message string)) *WSClient {
client := WSClient{
socket: gowebsocket.New(WS_URL),
}
client.socket.OnConnected = func(socket gowebsocket.Socket) {
client.socket.SendText("{\"op\":2,\"d\":{\"" + subscription + "\":" + subscription_data + "}}")
go client.ping()
}
client.socket.OnConnectError = func(err error, socket gowebsocket.Socket) {
log.Println("An error occured while connecting to Lanyard websocket server", err)
client.Destroy()
}
client.socket.OnTextMessage = func(message string, socket gowebsocket.Socket) {
if strings.Contains(message, "heartbeat_interval") {
return
}
onMessage(client, message)
}
client.socket.Connect()
return &client
}