-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
129 lines (111 loc) · 2.52 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
package rosetta
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
)
var (
client http.Client
)
type Client struct {
addr string
apiKey string
blockchain string
network string
}
func New(addr string, apiKey string) *Client {
c := &Client{addr, apiKey, "", ""}
return c
}
func (c *Client) SetBlockchain(chain string) {
c.blockchain = chain
}
func (c *Client) SetNetwork(network string) {
c.network = network
}
func (c *Client) callApi(path string, body interface{}) ([]byte, error) {
reqBytes, err := json.Marshal(body)
if err != nil {
return nil, err
}
url := c.addr + path
req, err := http.NewRequest("POST", url, bytes.NewBuffer(reqBytes))
if err != nil {
return nil, err
}
req.Header.Set("X-Api-Key", c.apiKey)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
resp, err := client.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode > 299 {
return nil, errors.New("Failed request: " + resp.Status)
}
defer resp.Body.Close()
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return bodyBytes, nil
}
func (c *Client) NetworkStatus() (*NetworkStatus, error) {
rBody := RosettaRequest{
NetworkIdentifier: NetworkIdentifier{
Blockchain: c.blockchain,
Network: c.network,
},
}
var result NetworkStatus
b, err := c.callApi("/network/status", rBody)
if err != nil {
return nil, err
}
err = json.Unmarshal(b, &result)
if err != nil {
return nil, err
}
return &result, nil
}
func (c *Client) Block(blockIdentifier BlockIdentifier) (*BlockResponse, error) {
rBody := RosettaRequest{
NetworkIdentifier: NetworkIdentifier{
Blockchain: c.blockchain,
Network: c.network,
},
BlockIdentifier: blockIdentifier,
}
var result BlockResponse
b, err := c.callApi("/block", rBody)
if err != nil {
return nil, err
}
err = json.Unmarshal(b, &result)
if err != nil {
return nil, err
}
return &result, nil
}
func (c *Client) Transaction(blockIdentifier BlockIdentifier, txIdentifier TransactionIdentifier) (*BlockTransactionResponse, error) {
rBody := RosettaRequest{
NetworkIdentifier: NetworkIdentifier{
Blockchain: c.blockchain,
Network: c.network,
},
BlockIdentifier: blockIdentifier,
TransactionIdentifier: txIdentifier,
}
var result BlockTransactionResponse
b, err := c.callApi("/block/transaction", rBody)
if err != nil {
return nil, err
}
err = json.Unmarshal(b, &result)
if err != nil {
return nil, err
}
return &result, nil
}