-
Notifications
You must be signed in to change notification settings - Fork 4
/
command.go
79 lines (67 loc) · 1.48 KB
/
command.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
package xrpl
import (
"encoding/json"
"github.com/gorilla/websocket"
)
func (c *Client) Subscribe(streams []string) (BaseResponse, error) {
req := BaseRequest{
"command": "subscribe",
"streams": streams,
}
res, err := c.Request(req)
if err != nil {
return nil, err
}
c.mutex.Lock()
for _, stream := range streams {
c.StreamSubscriptions[stream] = true
}
c.mutex.Unlock()
return res, nil
}
func (c *Client) Unsubscribe(streams []string) (BaseResponse, error) {
req := BaseRequest{
"command": "unsubscribe",
"streams": streams,
}
res, err := c.Request(req)
if err != nil {
return nil, err
}
c.mutex.Lock()
for _, stream := range streams {
delete(c.StreamSubscriptions, stream)
}
c.mutex.Unlock()
return res, nil
}
// Send a websocket request. This method takes a BaseRequest object and automatically adds
// incremental request ID to it.
//
// Example usage:
//
// req := BaseRequest{
// "command": "account_info",
// "account": "rG1QQv2nh2gr7RCZ1P8YYcBUKCCN633jCn",
// "ledger_index": "current",
// }
//
// err := client.Request(req, func(){})
func (c *Client) Request(req BaseRequest) (BaseResponse, error) {
requestId := c.NextID()
req["id"] = requestId
data, err := json.Marshal(req)
if err != nil {
return nil, err
}
ch := make(chan BaseResponse, 1)
c.mutex.Lock()
c.requestQueue[requestId] = ch
err = c.connection.WriteMessage(websocket.TextMessage, data)
if err != nil {
return nil, err
}
c.mutex.Unlock()
res := <-ch
return res, nil
}