-
Notifications
You must be signed in to change notification settings - Fork 4
/
client.go
78 lines (64 loc) · 1.98 KB
/
client.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
package bittrex
import (
"crypto/hmac"
"crypto/sha512"
"encoding/hex"
"errors"
"io/ioutil"
"net/http"
"strconv"
"strings"
"time"
)
type bittrexClient struct {
apiKey string
secretKey string
httpClient http.Client
}
func NewBittrexClient(apiKey string, secretKey string, client http.Client) *bittrexClient {
return &bittrexClient{apiKey: apiKey, secretKey: secretKey, httpClient: client}
}
func (this *bittrexClient) Do(method string, uri string, payload string, authenticate bool) ([]byte, error) {
request, err := http.NewRequest(method, uri, strings.NewReader(payload))
if err != nil {
return nil, err
}
if authenticate {
if this.Authenticate(request, payload, uri, method) != nil {
return nil, err
}
}
resp, err := this.httpClient.Do(request)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, err
}
func (this *bittrexClient) Authenticate(request *http.Request, payload string, uri string, method string) error {
if len(this.apiKey) == 0 || len(this.secretKey) == 0 {
err := errors.New("you need to set API Key and API Secret to call this method")
return err
}
timestamp := strconv.FormatInt(time.Now().UnixNano()/1000000, 10)
query := request.URL.Query()
request.URL.RawQuery = query.Encode()
hash := sha512.New()
_, err := hash.Write([]byte(payload))
contentHash := hex.EncodeToString(hash.Sum(nil))
preSigned := strings.Join([]string{timestamp, uri, method, contentHash}, "")
sigHash := hmac.New(sha512.New, []byte(this.secretKey))
_, err = sigHash.Write([]byte(preSigned))
signature := hex.EncodeToString(sigHash.Sum(nil))
request.Header.Add("Api-Key", this.apiKey)
request.Header.Add("Api-Timestamp", timestamp)
request.Header.Add("Api-Content-Hash", contentHash)
request.Header.Add("Api-Signature", signature)
request.Header.Add("Content-Type", "application/json;charset=utf-8")
request.Header.Add("Accept", "application/json")
return err
}