forked from f0cii/huobi-api
/
hbdm.go
121 lines (105 loc) · 2.47 KB
/
hbdm.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
package hbdm
import (
"fmt"
"github.com/kernight/huobi-api/utils"
"log"
"net/http"
"net/url"
"strings"
"time"
)
var (
defaultPostHeaders = map[string]string{"Content-Type": "application/json", "Accept-Language": "zh-cn"}
)
type ApiParameter struct {
Debug bool
AccessKey string
SecretKey string
EnablePrivateSign bool
BaseURL string
PrivateKeyPrime256 string
HttpClient *http.Client
ProxyURL string
}
type Client struct {
params *ApiParameter
domain string
httpClient *http.Client
}
func (c *Client) Heartbeat() (result HeartbeatResult, err error) {
var resp []byte
resp, err = utils.HttpGet(c.httpClient, "https://www.hbdm.com/heartbeat/", "", nil)
if err != nil {
return
}
err = json.Unmarshal(resp, &result)
return
}
func (c *Client) doGet(path string, params *url.Values, result interface{}) (resp []byte, err error) {
url := c.params.BaseURL + path + "?" + params.Encode()
resp, err = utils.HttpGet(
c.httpClient,
url,
"",
nil,
)
if err != nil {
return
}
if c.params.Debug {
log.Println(string(resp))
}
if result == nil {
return
}
err = json.Unmarshal(resp, result)
return
}
func (c *Client) doPost(path string, params *url.Values, result interface{}) (resp []byte, err error) {
c.sign("POST", path, params)
jsonD, _ := utils.ValuesToJson(*params)
url := c.params.BaseURL + path + "?" + params.Encode()
resp, err = utils.HttpPost(
c.httpClient,
url,
string(jsonD),
defaultPostHeaders,
)
if err != nil {
return
}
if c.params.Debug {
log.Println(string(resp))
}
if result == nil {
return
}
err = json.Unmarshal(resp, result)
return
}
func (c *Client) sign(reqMethod, path string, postForm *url.Values) error {
postForm.Set("AccessKeyId", c.params.AccessKey)
postForm.Set("SignatureMethod", "HmacSHA256")
postForm.Set("SignatureVersion", "2")
postForm.Set("Timestamp", time.Now().UTC().Format("2006-01-02T15:04:05"))
payload := fmt.Sprintf("%s\n%s\n%s\n%s",
reqMethod,
c.domain,
path,
postForm.Encode())
signature, _ := utils.GetParamHmacSHA256Base64Sign(c.params.SecretKey, payload)
postForm.Set("Signature", signature)
return nil
}
func NewClient(params *ApiParameter) *Client {
domain := strings.Replace(params.BaseURL, "https://", "", -1)
httpClient := params.HttpClient
if httpClient == nil {
httpClient = utils.DefaultHttpClient(params.ProxyURL)
}
return &Client{
params: params,
domain: domain,
httpClient: httpClient,
}
}