/
client.go
113 lines (97 loc) · 2.22 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
package linode
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
)
const (
// Linode API URL.
BaseURL = "https://api.linode.com/"
)
type httpPoster func(string, url.Values) (*http.Response, error)
type apiCaller func(string, map[string]interface{}) (json.RawMessage, error)
type argMarshaler func(interface{}) (map[string]interface{}, error)
// Client is the API client. It should be created by a call to
// NewClient().
type Client struct {
URL string
key string
post httpPoster
apiCall apiCaller
argMarshal argMarshaler
}
// NewClient returns a new client configured with the passed API key.
func NewClient(apiKey string) *Client {
c := &Client{
URL: BaseURL,
key: apiKey,
post: http.PostForm,
argMarshal: marshallArgs,
}
c.apiCall = c.liveAPICaller
return c
}
type apiError struct {
Code int `json:"ERRORCODE"`
Msg string `json:"ERRORMESSAGE"`
}
type apiResponse struct {
APIErrors []apiError `json:"ERRORARRAY"`
Data json.RawMessage `json:"DATA"`
}
func (c *Client) liveAPICaller(method string, args map[string]interface{}) (json.RawMessage, error) {
vals := url.Values{}
vals.Set("api_action", method)
vals.Set("api_key", c.key)
for k, t := range args {
switch v := t.(type) {
case string:
vals.Set(k, v)
case *string:
if v != nil {
vals.Set(k, *v)
}
case int:
vals.Set(k, strconv.Itoa(v))
case *int:
if v != nil {
vals.Set(k, strconv.Itoa(*v))
}
case bool:
vals.Set(k, fmt.Sprintf("%t", v))
case *bool:
if v != nil {
vals.Set(k, fmt.Sprintf("%t", *v))
}
default:
return nil, fmt.Errorf("cannot convert %s to string", k)
}
}
resp, err := c.post(c.URL, vals)
if resp != nil {
defer func() {
_ = resp.Body.Close()
}()
}
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
record(method, vals, body)
ret := apiResponse{}
err = json.Unmarshal(body, &ret)
if err != nil {
return nil, err
}
if len(ret.APIErrors) != 0 && ret.APIErrors[0].Code != 0 {
// Only return a single error for now.
return nil, fmt.Errorf("api: %d: %s", ret.APIErrors[0].Code, ret.APIErrors[0].Msg)
}
return ret.Data, nil
}