-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
152 lines (110 loc) · 2.34 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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
package socketify
import (
"encoding/json"
"fmt"
"github.com/gorilla/websocket"
"io"
"sync"
)
type Client struct {
*writer
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)
rawMiddleware func(update []byte)
}
func NewClient(address string) *Client {
ch := make(chan messageType)
cl := &Client{
address: address,
handlers: map[string]func(json.RawMessage){},
closed: make(chan bool),
writer: newWriter(ch, logger{}),
}
return cl
}
func (c *Client) SetRawHandler(fn func(message []byte)) *Client {
c.rawHandler = fn
return c
}
func (c *Client) SetRawMiddleware(fn func(message []byte)) *Client {
c.rawMiddleware = 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) SetOnClose(fn func(err error)) *Client {
c.onClose = fn
return c
}
func (c *Client) NextReader() (messageType int, r io.Reader, err error) {
return c.ws.NextReader()
}
func (c *Client) Connect() error {
conn, _, err := websocket.DefaultDialer.Dial(c.address, nil)
if err != nil {
return err
}
c.ws = conn
go c.writer.processWriter(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.rawMiddleware != nil {
go c.rawMiddleware(message)
}
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
}
c.handlersLock.Unlock()
}
}