forked from INFURA/go-ethlibs
/
http.go
90 lines (73 loc) · 2.03 KB
/
http.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
package node
import (
"bytes"
"context"
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"sync"
"time"
"github.com/INFURA/go-ethlibs/jsonrpc"
"github.com/pkg/errors"
)
func newHTTPTransport(ctx context.Context, parsedURL *url.URL) (transport, error) {
return &httpTransport{
rawURL: parsedURL.String(),
}, nil
}
type httpTransport struct {
rawURL string
client *http.Client
once sync.Once
}
func (t *httpTransport) Request(ctx context.Context, r *jsonrpc.Request) (*jsonrpc.RawResponse, error) {
b, err := json.Marshal(r)
if err != nil {
return nil, errors.Wrap(err, "could not decode request json")
}
body, err := t.dispatchBytes(ctx, b)
if err != nil {
return nil, errors.Wrap(err, "could not dispatch request")
}
jr := jsonrpc.RawResponse{}
err = json.Unmarshal(body, &jr)
if err != nil {
return nil, errors.Wrap(err, "could not decode response json")
}
return &jr, nil
}
func (t *httpTransport) Subscribe(ctx context.Context, r *jsonrpc.Request) (Subscription, error) {
return nil, errors.New("subscriptions not supported over HTTP")
}
func (t *httpTransport) IsBidirectional() bool {
return false
}
func (t *httpTransport) dispatchBytes(ctx context.Context, input []byte) ([]byte, error) {
t.once.Do(func() {
// Since this client is only ever used to access a single endpoint,
// we allow all the idle connections to point that host
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.MaxIdleConnsPerHost = tr.MaxIdleConns
t.client = &http.Client{
Timeout: 120 * time.Second,
Transport: tr,
}
})
r, err := http.NewRequest(http.MethodPost, t.rawURL, bytes.NewReader(input))
if err != nil {
return nil, errors.Wrap(err, "could not create http.Request")
}
r = r.WithContext(ctx)
r.Header.Add("Content-Type", "application/json")
resp, err := t.client.Do(r)
if err != nil {
return nil, errors.Wrap(err, "error in client.Do")
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, errors.Wrap(err, "error reading body")
}
return body, nil
}