forked from go-numb/go-ftx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
116 lines (97 loc) · 2.42 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
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
package rest
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"net/url"
"time"
"github.com/valyala/fasthttp"
)
type Response struct {
Result interface{} `json:"result,omitempty"`
Error string `json:"error,omitempty"`
Success bool `json:"success"`
}
func (p *Client) request(req Requester, results interface{}) error {
res, err := p.do(req)
if err != nil {
return err
}
if err := decode(res, results); err != nil {
return err
}
return nil
}
func signature(secret, body string) string {
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(body))
return hex.EncodeToString(mac.Sum(nil))
}
func (p *Client) newRequest(r Requester) *fasthttp.Request {
// avoid Pointer's butting
u, _ := url.ParseRequestURI(ENDPOINT)
u.Path = u.Path + r.Path()
u.RawQuery = r.Query()
req := fasthttp.AcquireRequest()
req.Header.SetMethod(r.Method())
req.SetRequestURI(u.String())
body := r.Payload()
req.SetBody(body)
if p.Auth != nil {
nonce := fmt.Sprintf("%d", int64(time.Now().UTC().UnixNano()/int64(time.Millisecond)))
payload := nonce + r.Method() + u.Path
if u.RawQuery != "" {
payload += "?" + u.RawQuery
}
payload += string(body)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("FTX-KEY", p.Auth.Key)
req.Header.Set("FTX-SIGN", p.Auth.Signature(payload))
req.Header.Set("FTX-TS", nonce)
// set id is there UseSubAccountID
subaccount := p.Auth.SubAccount()
if subaccount.Nickname != "" {
req.Header.Set("FTX-SUBACCOUNT", url.PathEscape(subaccount.Nickname))
}
}
return req
}
func (c *Client) do(r Requester) (*fasthttp.Response, error) {
req := c.newRequest(r)
// fasthttp for http2.0
res := fasthttp.AcquireResponse()
err := c.HTTPC.DoTimeout(req, res, c.HTTPTimeout)
if err != nil {
return nil, err
}
// fmt.Printf("%+v\n", string(res.Body()))
// no usefull headers
if res.StatusCode() != 200 {
var r = new(Response)
if err := json.Unmarshal(res.Body(), r); err != nil {
return nil, &APIError{
Status: res.StatusCode(),
Message: err.Error(),
}
}
if !r.Success {
return nil, &APIError{
Status: res.StatusCode(),
Message: r.Error,
}
}
}
return res, nil
}
func decode(res *fasthttp.Response, out interface{}) error {
var r = new(Response)
r.Result = out
if err := json.Unmarshal(res.Body(), r); err != nil {
return err
}
if !r.Success {
return fmt.Errorf("decode error")
}
return nil
}