forked from umbracle/ethgo
-
Notifications
You must be signed in to change notification settings - Fork 2
/
http.go
75 lines (64 loc) · 1.5 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
package transport
import (
"encoding/json"
"fmt"
"github.com/mgintoki/go-web3/jsonrpc/codec"
"github.com/valyala/fasthttp"
)
// HTTP is an http transport
type HTTP struct {
addr string
client *fasthttp.Client
}
func newHTTP(addr string) *HTTP {
return &HTTP{
addr: addr,
client: &fasthttp.Client{},
}
}
// Close implements the transport interface
func (h *HTTP) Close() error {
return nil
}
// Call implements the transport interface
func (h *HTTP) Call(method string, out interface{}, params ...interface{}) error {
// Encode json-rpc request
request := codec.Request{
JsonRPC: "2.0",
Method: method,
}
if len(params) > 0 {
data, err := json.Marshal(params)
if err != nil {
return err
}
request.Params = data
}
raw, err := json.Marshal(request)
if err != nil {
return err
}
req := fasthttp.AcquireRequest()
res := fasthttp.AcquireResponse()
defer fasthttp.ReleaseRequest(req)
defer fasthttp.ReleaseResponse(res)
req.SetRequestURI(h.addr)
req.Header.SetMethod("POST")
req.Header.SetContentType("application/json")
req.SetBody(raw)
if err := h.client.Do(req, res); err != nil {
return err
}
// Decode json-rpc response
var response codec.Response
if err := json.Unmarshal(res.Body(), &response); err != nil {
return fmt.Errorf("parse rpc response error : %s, and raw data is %s", err.Error(), string(res.Body()))
}
if response.Error != nil {
return response.Error
}
if err := json.Unmarshal(response.Result, out); err != nil {
return err
}
return nil
}