/
request.go
56 lines (44 loc) · 983 Bytes
/
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
package bitfinex
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/go-resty/resty/v2"
)
const (
Endpoint = "https://api-pub.bitfinex.com/v2"
)
var httpClient = resty.New().
SetHeader("Content-Type", "application/json").
SetBaseURL(Endpoint).
SetTimeout(10 * time.Second)
type Error struct {
Code int `json:"code,omitempty"`
Msg string `json:"msg,omitempty"`
}
func (err *Error) Error() string {
return fmt.Sprintf("[%d] %s", err.Code, err.Msg)
}
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{
Code: resp.StatusCode(),
Msg: resp.Status(),
}
}
return json.RawMessage(resp.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
}