-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
118 lines (88 loc) · 1.8 KB
/
client.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package socketify
import (
"encoding/json"
"fmt"
"github.com/gorilla/websocket"
"sync"
)
type Client struct {
address string
ws *websocket.Conn
handlersLock sync.Mutex
handlers map[string]func(json.RawMessage)
rawHandler func(message []byte)
onErr func(err error)
closed chan bool
onClose func(err error)
}
func NewClient(address string) *Client {
return &Client{
address: address,
handlers: map[string]func(json.RawMessage){},
closed: make(chan bool),
}
}
func (c *Client) SetRawHandler(fn func(message []byte)) *Client {
c.rawHandler = fn
return c
}
func (c *Client) SetUpdateTypeHandler(updateType string, fn func(message json.RawMessage)) *Client {
c.handlersLock.Lock()
defer c.handlersLock.Unlock()
c.handlers[updateType] = fn
return c
}
func (c *Client) SetOnError(fn func(err error)) *Client {
c.onErr = fn
return c
}
func (c *Client) Connect() error {
conn, _, err := websocket.DefaultDialer.Dial(c.address, nil)
if err != nil {
return err
}
c.ws = conn
go c.processUpdates()
<-c.closed
return fmt.Errorf("connection_closed")
}
func (c *Client) Close() {
c.close(fmt.Errorf("manually_called_close"))
}
func (c *Client) close(err error) {
defer c.ws.Close()
c.closed <- true
if c.onClose != nil {
c.onClose(err)
}
}
func (c *Client) handlerErr(err error) {
if c.onErr != nil {
c.onErr(err)
}
}
func (c *Client) processUpdates() {
for {
_, message, err := c.ws.ReadMessage()
if err != nil {
go c.handlerErr(err)
go c.close(err)
return
}
if c.rawHandler != nil {
go c.rawHandler(message)
continue
}
var u *Update
err = json.Unmarshal(message, &u)
if err != nil {
go c.handlerErr(err)
continue
}
c.handlersLock.Lock()
if handler, ok := c.handlers[u.Type]; ok {
go handler(u.Data)
continue
}
}
}