-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.go
77 lines (58 loc) · 1.43 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
package whitebit
import (
"encoding/json"
"io/ioutil"
"net/http"
)
type Whitebit struct {
ApiKey string
ApiSecret string
BaseURL string
}
type Client interface {
SendRequest(endpoint Endpoint) ([]byte, error)
}
func NewClient(apiKey string, apiSecret string) *Whitebit {
return &Whitebit{ApiKey: apiKey, ApiSecret: apiSecret, BaseURL: "https://whitebit.com"}
}
func (c *Whitebit) call(request *http.Request) ([]byte, int, error) {
client := http.Client{}
response, err := client.Do(request)
if err != nil {
return nil, http.StatusInternalServerError, err
}
defer response.Body.Close()
//receiving data
responseBody, err := ioutil.ReadAll(response.Body)
return responseBody, response.StatusCode, err
}
func (c *Whitebit) SendRequest(endpoint Endpoint) ([]byte, error) {
url := c.BaseURL + endpoint.Url()
var req *http.Request
var err error
if endpoint.IsAuthed() {
requestBody, err := json.Marshal(endpoint)
if err != nil {
return nil, err
}
req, err = CreateAuthedRequest(url, requestBody, c.ApiKey, c.ApiSecret)
if err != nil {
return nil, err
}
} else {
req, err = CreateRequest(url)
if err != nil {
return nil, err
}
}
response, status, err := c.call(req)
if err != nil {
return nil, err
}
if status != http.StatusOK && status != http.StatusCreated {
var validationError Error
_ = json.Unmarshal(response, &validationError)
return nil, validationError
}
return response, nil
}