forked from centrifugal/gocent
/
main.go
381 lines (344 loc) · 9.97 KB
/
main.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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
// The MIT License (MIT)
//
// Copyright (c) 2015, Alexandr Emelin
// Package gocent is a Go language API client for Centrifugo real-time messaging server.
//
// Usage example
//
// In example below we initialize new client with server URL address, project key, project
// secret and request timeout. Then publish data into channel, call presence and history
// for channel and finally show how to publish several messages in one POST request to API
// endpoint using internal command buffer.
//
// c := NewClient("http://localhost:8000", "development", "secret", 5*time.Second)
// ok, err := c.Publish("$public:chat", []byte(`{"input": "test"}`))
// if err != nil {
// println(err.Error())
// return
// }
// println(ok)
// presence, _ := c.Presence("$public:chat")
// fmt.Printf("%v", presence)
// history, _ := c.History("$public:chat")
// fmt.Printf("%v", history)
// _ = c.AddPublish("$public:chat", []byte(`{"input": "test1"}`))
// _ = c.AddPublish("$public:chat", []byte(`{"input": "test2"}`))
// _ = c.AddPublish("$public:chat", []byte(`{"input": "test3"}`))
// result, err := c.Send()
// println(len(result))
//
package gocent // import "github.com/centrifugal/gocent"
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"strings"
"sync"
"time"
"github.com/centrifugal/centrifugo/libcentrifugo"
"github.com/centrifugal/centrifugo/libcentrifugo/auth"
)
var (
// ErrClientNotEmpty can be returned when client with non empty commands buffer
// is used for single command send.
ErrClientNotEmpty = errors.New("client command buffer not empty, send commands or reset client")
// ErrMalformedResponse can be returned when server replied with invalid response.
ErrMalformedResponse = errors.New("malformed response returned from server")
)
// Client is API client for project registered in server.
type Client struct {
sync.RWMutex
Endpoint string
Key string
Secret string
Timeout time.Duration
cmds []Command
}
// Command represents API command to send.
type Command struct {
Method string `json:"method"`
Params map[string]interface{} `json:"params"`
}
// Response is a response of server on command sent.
type Response struct {
Method string
Error string
Body json.RawMessage
}
// Result is a slice of responses.
type Result []Response
// NewClient returns initialized client instance based on provided server address,
//project key, project secret and timeout.
func NewClient(addr, key, secret string, timeout time.Duration) *Client {
addr = strings.TrimRight(addr, "/")
if !strings.HasSuffix(addr, "/api") {
addr = addr + "/api"
}
apiEndpoint := addr + "/" + key
return &Client{
Endpoint: apiEndpoint,
Key: key,
Secret: secret,
Timeout: timeout,
cmds: []Command{},
}
}
func (c *Client) empty() bool {
c.RLock()
defer c.RUnlock()
return len(c.cmds) == 0
}
// Reset allows to clear client command buffer.
func (c *Client) Reset() {
c.Lock()
defer c.Unlock()
c.cmds = []Command{}
}
// AddPublish adds publish command to client command buffer but not actually
// send it until Send method explicitly called.
func (c *Client) AddPublish(channel string, data []byte) error {
c.Lock()
defer c.Unlock()
var raw json.RawMessage
raw = json.RawMessage(data)
cmd := Command{
Method: "publish",
Params: map[string]interface{}{
"channel": channel,
"data": &raw,
},
}
c.cmds = append(c.cmds, cmd)
return nil
}
// AddUnsubscribe adds unsubscribe command to client command buffer but not actually
// send it until Send method explicitly called.
func (c *Client) AddUnsubscribe(channel string, user string) error {
c.Lock()
defer c.Unlock()
cmd := Command{
Method: "unsubscribe",
Params: map[string]interface{}{
"channel": channel,
"user": user,
},
}
c.cmds = append(c.cmds, cmd)
return nil
}
// AddDisconnect adds disconnect command to client command buffer but not actually
// send it until Send method explicitly called.
func (c *Client) AddDisconnect(user string) error {
c.Lock()
defer c.Unlock()
cmd := Command{
Method: "disconnect",
Params: map[string]interface{}{
"user": user,
},
}
c.cmds = append(c.cmds, cmd)
return nil
}
// AddPresence adds presence command to client command buffer but not actually
// send it until Send method explicitly called.
func (c *Client) AddPresence(channel string) error {
c.Lock()
defer c.Unlock()
cmd := Command{
Method: "presence",
Params: map[string]interface{}{
"channel": channel,
},
}
c.cmds = append(c.cmds, cmd)
return nil
}
// AddHistory adds history command to client command buffer but not actually
// send it until Send method explicitly called.
func (c *Client) AddHistory(channel string) error {
c.Lock()
defer c.Unlock()
cmd := Command{
Method: "history",
Params: map[string]interface{}{
"channel": channel,
},
}
c.cmds = append(c.cmds, cmd)
return nil
}
// Publish sends publish command to server and returns boolean indicator of success and
// any error occurred in process.
func (c *Client) Publish(channel string, data []byte) (bool, error) {
if !c.empty() {
return false, ErrClientNotEmpty
}
c.AddPublish(channel, data)
c.Lock()
defer c.Unlock()
result, err := c.Send()
if err != nil {
return false, err
}
resp := result[0]
if resp.Error != "" {
return false, errors.New(resp.Error)
}
return DecodePublish(resp.Body)
}
// Unsubscribe sends unsubscribe command to server and returns boolean indicator of success and
// any error occurred in process.
func (c *Client) Unsubscribe(channel, user string) (bool, error) {
if !c.empty() {
return false, ErrClientNotEmpty
}
c.AddUnsubscribe(channel, user)
c.Lock()
defer c.Unlock()
result, err := c.Send()
if err != nil {
return false, err
}
resp := result[0]
if resp.Error != "" {
return false, errors.New(resp.Error)
}
return DecodeUnsubscribe(resp.Body)
}
// Disconnect sends disconnect command to server and returns boolean indicator of success and
// any error occurred in process.
func (c *Client) Disconnect(user string) (bool, error) {
if !c.empty() {
return false, ErrClientNotEmpty
}
c.AddDisconnect(user)
c.Lock()
defer c.Unlock()
result, err := c.Send()
if err != nil {
return false, err
}
resp := result[0]
if resp.Error != "" {
return false, errors.New(resp.Error)
}
return DecodeDisconnect(resp.Body)
}
// Presence sends presence command for channel to server and returns map with client
// information and any error occurred in process.
func (c *Client) Presence(channel string) (map[libcentrifugo.ConnID]libcentrifugo.ClientInfo, error) {
if !c.empty() {
return map[libcentrifugo.ConnID]libcentrifugo.ClientInfo{}, ErrClientNotEmpty
}
c.AddPresence(channel)
c.Lock()
defer c.Unlock()
result, err := c.Send()
if err != nil {
return map[libcentrifugo.ConnID]libcentrifugo.ClientInfo{}, err
}
resp := result[0]
if resp.Error != "" {
return map[libcentrifugo.ConnID]libcentrifugo.ClientInfo{}, errors.New(resp.Error)
}
return DecodePresence(resp.Body)
}
// History sends history command for channel to server and returns slice with
// messages and any error occurred in process.
func (c *Client) History(channel string) ([]libcentrifugo.Message, error) {
if !c.empty() {
return []libcentrifugo.Message{}, ErrClientNotEmpty
}
c.AddHistory(channel)
c.Lock()
defer c.Unlock()
result, err := c.Send()
if err != nil {
return []libcentrifugo.Message{}, err
}
resp := result[0]
if resp.Error != "" {
return []libcentrifugo.Message{}, errors.New(resp.Error)
}
return DecodeHistory(resp.Body)
}
// DecodePublish allows to decode response body of publish command to get
// success flag from it. Currently no error in response means success - so nothing
// to do here yet.
func DecodePublish(body []byte) (bool, error) {
return true, nil
}
// DecodeUnsubscribe allows to decode response body of unsubscribe command to get
// success flag from it. Currently no error in response means success - so nothing
// to do here yet.
func DecodeUnsubscribe(body []byte) (bool, error) {
return true, nil
}
// DecodeDisconnect allows to decode response body of disconnect command to get
// success flag from it. Currently no error in response means success - so nothing
// to do here yet.
func DecodeDisconnect(body []byte) (bool, error) {
return true, nil
}
// DecodeHistory allows to decode history response body to get a slice of messages.
func DecodeHistory(body []byte) ([]libcentrifugo.Message, error) {
var d libcentrifugo.HistoryBody
err := json.Unmarshal(body, &d)
if err != nil {
return []libcentrifugo.Message{}, err
}
return d.Data, nil
}
// DecodePresence allows to decode presence response body to get a map of clients.
func DecodePresence(body []byte) (map[libcentrifugo.ConnID]libcentrifugo.ClientInfo, error) {
var d libcentrifugo.PresenceBody
err := json.Unmarshal(body, &d)
if err != nil {
return map[libcentrifugo.ConnID]libcentrifugo.ClientInfo{}, err
}
return d.Data, nil
}
// Send actually makes API POST request to server sending all buffered commands in
// one request. Using this method you should manually decode all responses in
// returned Result.
func (c *Client) Send() (Result, error) {
cmds := c.cmds
c.cmds = []Command{}
result, err := c.send(cmds)
if err != nil {
return Result{}, err
}
if len(result) != len(cmds) {
return Result{}, ErrMalformedResponse
}
return result, nil
}
func (c *Client) send(cmds []Command) (Result, error) {
data, err := json.Marshal(cmds)
if err != nil {
return Result{}, err
}
client := &http.Client{}
client.Timeout = c.Timeout
r, err := http.NewRequest("POST", c.Endpoint, bytes.NewBuffer(data))
if err != nil {
return Result{}, err
}
r.Header.Set("X-API-Sign", auth.GenerateApiSign(c.Secret, c.Key, data))
r.Header.Add("Content-Type", "application/json")
resp, err := client.Do(r)
if err != nil {
return Result{}, err
}
if resp.StatusCode != http.StatusOK {
return Result{}, errors.New("wrong status code: " + resp.Status)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
var result Result
err = json.Unmarshal(body, &result)
return result, err
}