-
Notifications
You must be signed in to change notification settings - Fork 98
/
Copy pathcommon.go
282 lines (240 loc) · 7.95 KB
/
common.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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
package common
import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"github.com/algorand/go-algorand-sdk/v2/encoding/json"
"github.com/algorand/go-algorand-sdk/v2/encoding/msgpack"
"github.com/google/go-querystring/query"
)
// rawRequestPaths is a set of paths where the body should not be urlencoded
var rawRequestPaths = map[string]bool{
"/v2/transactions": true,
"/v2/teal/compile": true,
"/v2/teal/disassemble": true,
"/v2/teal/dryrun": true,
"/v2/transactions/simulate": true,
}
// Header is a struct for custom headers.
type Header struct {
Key string
Value string
}
// Client manages the REST interface for a calling user.
type Client struct {
serverURL url.URL
apiHeader string
apiToken string
headers []*Header
transport http.RoundTripper
}
// MakeClient is the factory for constructing a Client for a given endpoint.
func MakeClient(address string, apiHeader, apiToken string) (c *Client, err error) {
url, err := url.Parse(address)
if err != nil {
return
}
c = &Client{
serverURL: *url,
apiHeader: apiHeader,
apiToken: apiToken,
}
return
}
// MakeClientWithHeaders is the factory for constructing a Client for a given endpoint with additional user defined headers.
func MakeClientWithHeaders(address string, apiHeader, apiToken string, headers []*Header) (c *Client, err error) {
c, err = MakeClient(address, apiHeader, apiToken)
if err != nil {
return
}
c.headers = append(c.headers, headers...)
return
}
// MakeClientWithTransport is the factory for constructing a Client for a given endpoint with a
// custom HTTP Transport as well as optional additional user defined headers.
func MakeClientWithTransport(address string, apiHeader, apiToken string, headers []*Header, transport http.RoundTripper) (c *Client, err error) {
c, err = MakeClientWithHeaders(address, apiHeader, apiToken, headers)
if err != nil {
return
}
c.transport = transport
return
}
type BadRequest error
type InvalidToken error
type NotFound error
type InternalError error
// extractError checks if the response signifies an error.
// If so, it returns the error.
// Otherwise, it returns nil.
func extractError(code int, errorBuf []byte) error {
if code >= 200 && code < 300 {
return nil
}
wrappedError := fmt.Errorf("HTTP %v: %s", code, errorBuf)
switch code {
case 400:
return BadRequest(wrappedError)
case 401:
return InvalidToken(wrappedError)
case 404:
return NotFound(wrappedError)
case 500:
return InternalError(wrappedError)
default:
return wrappedError
}
}
// mergeRawQueries merges two raw queries, appending an "&" if both are non-empty
func mergeRawQueries(q1, q2 string) string {
if q1 == "" {
return q2
}
if q2 == "" {
return q1
}
return q1 + "&" + q2
}
// submitFormRaw is a helper used for submitting (ex.) GETs and POSTs to the server
func (client *Client) submitFormRaw(ctx context.Context, path string, params interface{}, requestMethod string, encodeJSON bool, headers []*Header, body interface{}) (resp *http.Response, err error) {
queryURL := client.serverURL
queryURL.Path += path
var (
req *http.Request
bodyReader io.Reader
v url.Values
)
if params != nil {
v, err = query.Values(params)
if err != nil {
return nil, err
}
}
if requestMethod == "POST" && rawRequestPaths[path] {
reqBytes, ok := body.([]byte)
if !ok {
return nil, fmt.Errorf("couldn't decode raw body as bytes")
}
bodyReader = bytes.NewBuffer(reqBytes)
} else if encodeJSON {
jsonValue := json.Encode(params)
bodyReader = bytes.NewBuffer(jsonValue)
}
queryURL.RawQuery = mergeRawQueries(queryURL.RawQuery, v.Encode())
req, err = http.NewRequest(requestMethod, queryURL.String(), bodyReader)
if err != nil {
return nil, err
}
// Supply the client token.
req.Header.Set(client.apiHeader, client.apiToken)
// Add the client headers.
for _, header := range client.headers {
req.Header.Add(header.Key, header.Value)
}
// Add the request headers.
for _, header := range headers {
req.Header.Add(header.Key, header.Value)
}
httpClient := &http.Client{Transport: client.transport}
req = req.WithContext(ctx)
resp, err = httpClient.Do(req)
if err != nil {
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
return nil, err
}
return resp, nil
}
func (client *Client) submitForm(ctx context.Context, response interface{}, path string, params interface{}, requestMethod string, encodeJSON bool, headers []*Header, body interface{}) error {
resp, err := client.submitFormRaw(ctx, path, params, requestMethod, encodeJSON, headers, body)
if err != nil {
return err
}
defer resp.Body.Close()
var bodyBytes []byte
bodyBytes, err = ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
responseErr := extractError(resp.StatusCode, bodyBytes)
// The caller wants a string
if strResponse, ok := response.(*string); ok {
*strResponse = string(bodyBytes)
return responseErr
}
// Attempt to unmarshal a response regardless of whether or not there was an error.
err = json.LenientDecode(bodyBytes, response)
if responseErr != nil {
// Even if there was an unmarshalling error, return the HTTP error first if there was one.
return responseErr
}
return err
}
// Delete performs a DELETE request to the specific path against the server
func (client *Client) Delete(ctx context.Context, response interface{}, path string, params interface{}, headers []*Header) error {
return client.submitForm(ctx, response, path, params, "DELETE", false /* encodeJSON */, headers, nil)
}
// Get performs a GET request to the specific path against the server
func (client *Client) Get(ctx context.Context, response interface{}, path string, params interface{}, headers []*Header) error {
return client.submitForm(ctx, response, path, params, "GET", false /* encodeJSON */, headers, nil)
}
// GetRaw performs a GET request to the specific path against the server and returns the raw body bytes.
func (client *Client) GetRaw(ctx context.Context, path string, params interface{}, headers []*Header) (response []byte, err error) {
var resp *http.Response
resp, err = client.submitFormRaw(ctx, path, params, "GET", false /* encodeJSON */, headers, nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var bodyBytes []byte
bodyBytes, err = ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return bodyBytes, extractError(resp.StatusCode, bodyBytes)
}
// GetRawMsgpack performs a GET request to the specific path against the server and returns the decoded messagepack response.
func (client *Client) GetRawMsgpack(ctx context.Context, response interface{}, path string, params interface{}, headers []*Header) error {
resp, err := client.submitFormRaw(ctx, path, params, "GET", false /* encodeJSON */, headers, nil)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
var bodyBytes []byte
bodyBytes, err = ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %+v", err)
}
return extractError(resp.StatusCode, bodyBytes)
}
dec := msgpack.NewLenientDecoder(resp.Body)
return dec.Decode(&response)
}
// Post sends a POST request to the given path with the given body object.
// No query parameters will be sent if body is nil.
// response must be a pointer to an object as post writes the response there.
func (client *Client) Post(ctx context.Context, response interface{}, path string, params interface{}, headers []*Header, body interface{}) error {
return client.submitForm(ctx, response, path, params, "POST", true /* encodeJSON */, headers, body)
}
// Helper function for correctly formatting and escaping URL path parameters.
// Used in the generated API client code.
func EscapeParams(params ...interface{}) []interface{} {
paramsStr := make([]interface{}, len(params))
for i, param := range params {
switch v := param.(type) {
case string:
paramsStr[i] = url.PathEscape(v)
default:
paramsStr[i] = fmt.Sprintf("%v", v)
}
}
return paramsStr
}