/
client.go
94 lines (81 loc) · 1.95 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package coinbase
import (
"bytes"
"encoding/json"
"errors"
"io"
"io/ioutil"
"net/http"
)
const (
// ENDPOINT defaults to https://api.commerce.coinbase.com
ENDPOINT = "https://api.commerce.coinbase.com"
// API_VERSION since version two you have to
API_VERSION = "2018-03-22"
)
// If Endpoint or ApiVersion aren't defined the library will use the consts value
type APIClient struct {
Key string
Endpoint string
ApiVersion string
Charge *ChargeService
}
func Client(api_key string) (client APIClient) {
client.Key = api_key
client.Charge = new(ChargeService)
client.Charge.Api = &client
return
}
// Fetch is wrapper for http request made to coinbase and also handel all other cases
func (a *APIClient) Fetch(method, path string, body interface{}) (interface{}, error) {
if a.Endpoint == "" {
a.Endpoint = ENDPOINT // default endpoint
}
if a.ApiVersion == "" {
a.ApiVersion = API_VERSION // default api version
}
var bodyBuffered io.Reader
if body != nil {
var data []byte
var err error
switch body.(type) {
case string:
data = []byte(body.(string))
default:
data, err = json.Marshal(body)
if err != nil {
return nil, err
}
}
bodyBuffered = bytes.NewBuffer(data)
}
req, err := http.NewRequest(method, a.Endpoint+path, bodyBuffered)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CC-Version", a.ApiVersion)
req.Header.Set("X-CC-Api-Key", a.Key)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return errors.New(string(bodyBytes)), nil
}
responseBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
response := make(map[string]interface{})
err = json.Unmarshal(responseBody, &response)
if err != nil {
return nil, err
}
return response, nil
}