-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fixes #1 - Added XRPL websocket reconnection handler
- Loading branch information
Showing
4 changed files
with
226 additions
and
111 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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 | ||
} |
Oops, something went wrong.