-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
90 lines (76 loc) · 2.1 KB
/
client.go
File metadata and controls
90 lines (76 loc) · 2.1 KB
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
// Copyright (c) 2015 LunaNode Hosting Inc. All right reserved.
// Use of this source code is governed by the MIT License. See LICENSE file.
package linode
import "encoding/json"
import "fmt"
import "io/ioutil"
import "net/http"
import "net/url"
const API_URL = "https://api.linode.com/"
// Linode API client.
// Note that Linode API encodes booleans as JSON integers, and returned objects will correspondingly contain integer fields.
type Client struct {
// The Linode API key.
APIKey string
// An HTTP client to perform API requests.
HTTPClient *http.Client
apiURL string
}
type apiError struct {
Code int `json:"ERRORCODE"`
Message string `json:"ERRORMESSAGE"`
}
type genericResponse struct {
Errors []apiError `json:"ERRORARRAY"`
Action string `json:"ACTION"`
Data interface{} `json:"DATA"`
}
func NewClient(apiKey string) *Client {
return &Client{
APIKey: apiKey,
HTTPClient: &http.Client{},
apiURL: API_URL,
}
}
func (client *Client) request(action string, params map[string]string, dataTarget interface{}) error {
// setup post parameters
postParams := make(url.Values)
postParams.Set("api_key", client.APIKey)
postParams.Set("api_action", action)
if params != nil {
for key, value := range params {
postParams.Set(key, value)
}
}
// determine URL to use
apiURL := API_URL
if client.apiURL != "" {
apiURL = client.apiURL
}
// do request
response, err := client.HTTPClient.PostForm(apiURL, postParams)
if err != nil {
return err
}
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}
// unmarshal json
responseTarget := new(genericResponse)
responseTarget.Data = dataTarget
err = json.Unmarshal(contents, responseTarget)
if err != nil {
return err
} else if responseTarget.Action != action {
return fmt.Errorf("expected %s for API response action, but got %s", action, responseTarget.Action)
}
// check for non-0 errors (0 is "ok" error)
for _, apiErr := range responseTarget.Errors {
if apiErr.Code != 0 {
return fmt.Errorf("API error (%s) %d: %s", action, apiErr.Code, apiErr.Message)
}
}
return nil
}