-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpc.go
116 lines (95 loc) · 2.39 KB
/
rpc.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
package gelato
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"time"
)
var (
contentTypeJSON = "application/json"
dialTimeout = 60 * time.Second
httpClientTimeout = 30 * time.Minute
callTimeout = 30 * time.Minute
transport = &http.Transport{
Dial: (&net.Dialer{
Timeout: dialTimeout,
}).Dial,
}
httpClient = &http.Client{
Transport: transport,
Timeout: httpClientTimeout,
}
)
// PostResponse is returned from a Gelato relayer after POSTing a request
type PostResponse struct {
TaskID string `json"taskId"`
}
func postRPC(endpoint string, data interface{}) (*PostResponse, error) {
bz, err := json.Marshal(data)
if err != nil {
return nil, err
}
buf := &bytes.Buffer{}
_, err = buf.Write(bz)
if err != nil {
return nil, err
}
r, err := http.NewRequest("POST", endpoint, buf)
if err != nil {
return nil, fmt.Errorf("failed to create HTTP request: %w", err)
}
r.Header.Set("Content-Type", contentTypeJSON)
ctx, cancel := context.WithTimeout(context.Background(), callTimeout)
defer cancel()
r = r.WithContext(ctx)
resp, err := httpClient.Do(r)
if err != nil {
return nil, fmt.Errorf("failed to post request: %w", err)
}
defer func() {
_ = resp.Body.Close()
}()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
var pr *PostResponse
if err = json.Unmarshal(body, &pr); err != nil {
return nil, err
}
return pr, nil
}
// TODO: update this type https://docs.gelato.network/developer-products/gelato-relay-sdk/request-types#querying-task-status
type GetResponse struct {
Message string `json:"message"`
}
func getRPC(endpoint string) (*GetResponse, error) {
r, err := http.NewRequest("GET", endpoint, nil)
if err != nil {
return nil, fmt.Errorf("failed to create HTTP request: %w", err)
}
r.Header.Set("Content-Type", contentTypeJSON)
ctx, cancel := context.WithTimeout(context.Background(), callTimeout)
defer cancel()
r = r.WithContext(ctx)
resp, err := httpClient.Do(r)
if err != nil {
return nil, fmt.Errorf("failed to post request: %w", err)
}
defer func() {
_ = resp.Body.Close()
}()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
var gr *GetResponse
if err = json.Unmarshal(body, &gr); err != nil {
return nil, err
}
return gr, nil
}