/
request.go
63 lines (52 loc) · 1.12 KB
/
request.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
package ftx
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/go-resty/resty/v2"
)
const (
Endpoint = "https://ftx.com/api"
)
var httpClient = resty.New().
SetHeader("Content-Type", "application/json").
SetBaseURL(Endpoint).
SetTimeout(10 * time.Second)
type Error struct {
Success bool `json:"success"`
Message string `json:"error,omitempty"`
}
func (err *Error) Error() string {
return err.Message
}
func Request(ctx context.Context) *resty.Request {
return httpClient.R().SetContext(ctx)
}
func DecodeResponse(resp *resty.Response) ([]byte, error) {
if resp.IsError() {
return nil, &Error{
Message: fmt.Sprintf("[%d] %s", resp.StatusCode(), resp.Status()),
}
}
var result struct {
Error
Body json.RawMessage `json:"result"`
}
if err := json.Unmarshal(resp.Body(), &result); err != nil {
return nil, err
} else if !result.Success {
return nil, &result.Error
}
return result.Body, nil
}
func UnmarshalResponse(resp *resty.Response, v interface{}) error {
data, err := DecodeResponse(resp)
if err != nil {
return err
}
if v != nil {
return json.Unmarshal(data, v)
}
return nil
}