forked from aviate-labs/agent-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
80 lines (68 loc) · 1.76 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
package agent
import (
"bytes"
"fmt"
"io"
"net/http"
"net/url"
"path"
"github.com/aviate-labs/agent-go/principal"
"github.com/fxamacker/cbor/v2"
)
type Client struct {
client http.Client
config ClientConfig
}
func NewClient(cfg ClientConfig) Client {
return Client{
client: http.Client{},
config: cfg,
}
}
func (c Client) Status() (Status, error) {
raw, err := c.get("/api/v2/status")
if err != nil {
return Status{}, err
}
var status Status
return status, cbor.Unmarshal(raw, &status)
}
func (c Client) call(canisterID principal.Principal, data []byte) ([]byte, error) {
return c.post("call", canisterID, data, 202)
}
func (c Client) get(path string) ([]byte, error) {
resp, err := c.client.Get(c.url(path))
if err != nil {
return nil, err
}
return io.ReadAll(resp.Body)
}
func (c Client) post(path string, canisterID principal.Principal, data []byte, statusCorePass int) ([]byte, error) {
url := c.url(fmt.Sprintf("/api/v2/canister/%s/%s", canisterID.Encode(), path))
resp, err := c.client.Post(url, "application/cbor", bytes.NewBuffer(data))
if err != nil {
return nil, err
}
switch resp.StatusCode {
case statusCorePass:
defer resp.Body.Close()
return io.ReadAll(resp.Body)
default:
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("(%d) %s: %s", resp.StatusCode, resp.Status, body)
}
}
func (c Client) query(canisterID principal.Principal, data []byte) ([]byte, error) {
return c.post("query", canisterID, data, 200)
}
func (c Client) readState(canisterID principal.Principal, data []byte) ([]byte, error) {
return c.post("read_state", canisterID, data, 200)
}
func (c Client) url(p string) string {
url := *c.config.Host
url.Path = path.Join(url.Path, p)
return url.String()
}
type ClientConfig struct {
Host *url.URL
}