-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi_client.go
156 lines (124 loc) · 3.68 KB
/
api_client.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
package fireblocksdk
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
"github.com/hashicorp/go-retryablehttp"
"github.com/pkg/errors"
)
const (
APIVERSION string = "v1"
)
type IAPIClient interface {
DoPostRequest(path string, body interface{}, opts ...func(*PostRequestOption)) ([]byte, int, error)
DoGetRequest(path string, q url.Values) ([]byte, int, error)
DoPutRequest(path string, body interface{}) ([]byte, int, error)
DoDeleteRequest(path string) ([]byte, int, error)
}
type APIClient struct {
httpClient *retryablehttp.Client
auth IAuthProvider
baseURL string
}
func NewAPIClient(auth IAuthProvider, baseURL string) *APIClient {
client := retryablehttp.NewClient()
return &APIClient{client, auth, baseURL}
}
func (api *APIClient) makeRequest(method, path string, body interface{}) ([]byte, int, error) {
var (
status = http.StatusInternalServerError
bodyJSON = []byte("")
requestErr error
)
if method != http.MethodGet && body != nil {
var err error
bodyJSON, err = json.Marshal(body)
if err != nil {
return nil, status, errors.Wrap(err, "failed to marshal body")
}
}
jwtToken, err := api.auth.SignJwt(path, bodyJSON)
if err != nil {
return nil, status, errors.Wrap(err, "failed to sign request")
}
path = fmt.Sprintf("%s%s", api.baseURL, path)
req, err := retryablehttp.NewRequest(method, path, prepareBody(bodyJSON))
if err != nil {
return nil, status, errors.Wrap(err, "failed to create request")
}
req.Header.Add("X-API-Key", api.auth.GetAPIKey())
req.Header.Add("Authorization", fmt.Sprintf(`Bearer %s`, jwtToken))
req.Header.Set("Content-Type", "application/json; charset=UTF-8")
resp, err := api.httpClient.Do(req)
if err != nil {
return nil, status, errors.Wrapf(err, "failed to do request: %s", path)
}
var result []byte
if resp != nil && resp.Body != nil {
//goland:noinspection GoUnhandledErrorResult
defer resp.Body.Close()
status = resp.StatusCode
log.Printf(
"[%s] %s: status: %s, code: %d, content-length: %d",
method,
path,
resp.Status,
resp.StatusCode,
resp.ContentLength,
)
responseBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return result, status, errors.Wrap(err, "failed to parse response body")
}
result = responseBody
if status >= 400 {
sdkErr := &sdkError{}
errM := json.Unmarshal(result, sdkErr)
if errM == nil {
sdkErr.Path = fmt.Sprintf("%s %s", method, path)
requestErr = sdkErr
}
}
}
return result, status, requestErr
}
func (api *APIClient) DoPostRequest(path string, body interface{}, opts ...func(*PostRequestOption)) ([]byte, int, error) {
path = api.GetRelativePath(path)
return api.makeRequest(http.MethodPost, path, body)
}
func (api *APIClient) DoGetRequest(path string, q url.Values) ([]byte, int, error) {
query := ""
path = api.GetRelativePath(path)
if q != nil {
query = q.Encode()
path = fmt.Sprintf(`%s?%s`, path, query)
}
return api.makeRequest(http.MethodGet, path, []byte(query))
}
func (api *APIClient) DoPutRequest(path string, body interface{}) ([]byte, int, error) {
path = api.GetRelativePath(path)
return api.makeRequest(http.MethodPut, path, body)
}
func (api *APIClient) DoDeleteRequest(path string) ([]byte, int, error) {
path = api.GetRelativePath(path)
return api.makeRequest(http.MethodDelete, path, nil)
}
// GetRelativePath returns path without baseURL
func (api *APIClient) GetRelativePath(path string) string {
return fmt.Sprintf(`/%s%s`, APIVERSION, path)
}
func prepareBody(encodedBody []byte) io.ReadCloser {
if string(encodedBody) == "{}" {
encodedBody = []byte("")
}
return ioutil.NopCloser(
strings.NewReader(
string(encodedBody),
),
)
}