forked from forbole/juno
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient.go
More file actions
71 lines (60 loc) · 1.69 KB
/
client.go
File metadata and controls
71 lines (60 loc) · 1.69 KB
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
package jsonrpc2
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
urlpkg "net/url"
)
// Client represents a JSON-RPC client
type Client struct {
url string
httpClient *http.Client
}
// NewClient creates a new Client instance
func NewClient(url string, httpClient *http.Client) (*Client, error) {
if _, err := urlpkg.Parse(url); err != nil {
return nil, fmt.Errorf("invalid url: %w", err)
}
return &Client{
url: url,
httpClient: httpClient,
}, nil
}
// Call allows to perform an RPC call to the given method with the provided params
func (c *Client) Call(ctx context.Context, method string, params any, result any) error {
paramsJSON, err := json.Marshal(params)
if err != nil {
return fmt.Errorf("error while unmarshalling params: %w", err)
}
req := NewRequest(-1, method, paramsJSON)
reqJSON, _ := json.Marshal(req)
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, c.url, bytes.NewReader(reqJSON))
if err != nil {
return fmt.Errorf("error while performing http request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpResp, err := c.httpClient.Do(httpReq)
if err != nil {
return err
}
defer func() {
_, _ = io.Copy(io.Discard, httpResp.Body)
_ = httpResp.Body.Close()
}()
var resp Response
err = json.NewDecoder(httpResp.Body).Decode(&resp)
if err != nil {
return fmt.Errorf("error while unmarshalling response: status code %d: %w", httpResp.StatusCode, err)
}
if resp.Error != nil {
return fmt.Errorf("rpc error: status code %d: %w", httpResp.StatusCode, resp.Error)
}
err = json.Unmarshal(resp.Result, result)
if err != nil {
return fmt.Errorf("unmarshal result: %w", err)
}
return nil
}