-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
84 lines (63 loc) · 1.45 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
package go_cloudflare
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
type Client struct {
Token string
Email string
URL string
HttpHandler *http.Client
}
func NewClient(email string, token string) (*Client, error) {
client := Client{
Token: token,
Email: email,
URL: "https://www.cloudflare.com/api_json.html",
HttpHandler: http.DefaultClient,
}
return &client, nil
}
func (c *Client) NewRequest(params map[string]string, method string, action string) (*http.Request, error) {
data := url.Values{}
u, err := url.Parse(c.URL)
if err != nil {
return nil, fmt.Errorf("Error parsing base URL: %s", err)
}
data.Add("email", c.Email)
data.Add("tkn", c.Token)
data.Add("a", action)
for k, v := range params {
data.Add(k, v)
}
u.RawQuery = data.Encode()
req, err := http.NewRequest(method, u.String(), nil)
if err != nil {
return nil, fmt.Errorf("Error creating request: %s", err)
}
return req, nil
}
func decodeBody(resp *http.Response, out interface{}) error {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if err = json.Unmarshal(body, &out); err != nil {
return err
}
return nil
}
func checkResponse(resp *http.Response, err error) (*http.Response, error) {
if err != nil {
return resp, err
}
switch i := resp.StatusCode; {
case i == 200:
return resp, nil
default:
return nil, fmt.Errorf("API Error: %s", resp.Status)
}
}