-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
131 lines (101 loc) · 2.27 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
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
122
123
124
125
126
127
128
129
130
131
package resellerclub
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"net/url"
)
type Client struct {
userID string
key string
Domains *Domains
Customers *Customers
}
func New(userID string, key string) *Client {
client := &Client{
userID: userID,
key: key,
}
client.Domains = &Domains{client}
client.Customers = &Customers{client}
return client
}
func (client *Client) url(path string) *url.URL {
u, _ := url.Parse(endpoint)
q := u.Query()
q.Set("auth-userid", client.userID)
q.Set("api-key", client.key)
u.Path += path
u.RawQuery = q.Encode()
return u
}
func (client *Client) get(url string, target errorChecker) error {
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
return client.request(resp, target)
}
func (client *Client) post(url string, target errorChecker) error {
resp, err := http.Post(url, "text/plain", nil)
if err != nil {
return err
}
defer resp.Body.Close()
return client.request(resp, target)
}
func (client *Client) request(resp *http.Response, target errorChecker) error {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return somethingWentWrong(string(body))
}
if len(body) > 0 && body[0] != '{' {
return errors.New(string(body))
}
err = json.Unmarshal(body, target)
if err != nil {
return somethingWentWrong(string(body))
}
if err = target.Err(); err != nil {
return err
}
return nil
}
func (client *Client) getInt64(url string) (int64, error) {
resp, err := http.Get(url)
if err != nil {
return 0, err
}
defer resp.Body.Close()
return client.requestInt64(resp)
}
func (client *Client) postInt64(url string) (int64, error) {
resp, err := http.Post(url, "text/plain", nil)
if err != nil {
return 0, err
}
defer resp.Body.Close()
return client.requestInt64(resp)
}
func (client *Client) requestInt64(resp *http.Response) (int64, error) {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return 0, somethingWentWrong(string(body))
}
var i int64
err = json.Unmarshal(body, &i)
if err != nil {
var e errorResponse
err = json.Unmarshal(body, &e)
if err != nil {
return 0, somethingWentWrong(string(body))
}
if err = e.Err(); err != nil {
return 0, err
}
return 0, somethingWentWrong(string(body))
}
return i, nil
}