forked from ava-labs/avalanchego
-
Notifications
You must be signed in to change notification settings - Fork 4
/
json.go
63 lines (53 loc) · 1.47 KB
/
json.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
// Copyright (C) 2019-2022, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package rpc
import (
"bytes"
"context"
"fmt"
"net/http"
"net/url"
rpc "github.com/gorilla/rpc/v2/json2"
)
func SendJSONRequest(
ctx context.Context,
uri *url.URL,
method string,
params interface{},
reply interface{},
options ...Option,
) error {
requestBodyBytes, err := rpc.EncodeClientRequest(method, params)
if err != nil {
return fmt.Errorf("failed to encode client params: %w", err)
}
ops := NewOptions(options)
uri.RawQuery = ops.queryParams.Encode()
request, err := http.NewRequestWithContext(
ctx,
"POST",
uri.String(),
bytes.NewBuffer(requestBodyBytes),
)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
request.Header = ops.headers
request.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(request)
if err != nil {
return fmt.Errorf("failed to issue request: %w", err)
}
// Return an error for any non successful status code
if resp.StatusCode < 200 || resp.StatusCode > 299 {
// Drop any error during close to report the original error
_ = resp.Body.Close()
return fmt.Errorf("received status code: %d", resp.StatusCode)
}
if err := rpc.DecodeClientResponse(resp.Body, reply); err != nil {
// Drop any error during close to report the original error
_ = resp.Body.Close()
return fmt.Errorf("failed to decode client response: %w", err)
}
return resp.Body.Close()
}