forked from civo/civogo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
254 lines (209 loc) · 7.02 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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
package civogo
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"net/url"
"strings"
)
// Version represents the version of the civogo lib
const Version = "0.2.21"
// Client is the means of connecting to the Civo API service
type Client struct {
BaseURL *url.URL
UserAgent string
APIKey string
Region string
LastJSONResponse string
httpClient *http.Client
}
// HTTPError is the error returned when the API fails with an HTTP error
type HTTPError struct {
Code int
Status string
Reason string
}
// Result is the result of a SimpleResponse
type Result string
// SimpleResponse is a structure that returns success and/or any error
type SimpleResponse struct {
ID string `json:"id"`
Result Result `json:"result"`
ErrorCode string `json:"code"`
ErrorReason string `json:"reason"`
ErrorDetails string `json:"details"`
}
// ResultSuccess represents a successful SimpleResponse
const ResultSuccess = "success"
func (e HTTPError) Error() string {
return fmt.Sprintf("%d: %s, %s", e.Code, e.Status, e.Reason)
}
// NewClientWithURL initializes a Client with a specific API URL
func NewClientWithURL(apiKey, civoAPIURL, region string) (*Client, error) {
if apiKey == "" {
err := errors.New("no API Key supplied, this is required")
return nil, NoAPIKeySuppliedError.wrap(err)
}
parsedURL, err := url.Parse(civoAPIURL)
if err != nil {
return nil, err
}
var httpTransport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
}
client := &Client{
BaseURL: parsedURL,
UserAgent: "civogo/" + Version,
APIKey: apiKey,
Region: region,
httpClient: &http.Client{
Transport: httpTransport,
},
}
return client, nil
}
// NewClient initializes a Client connecting to the production API
func NewClient(apiKey, region string) (*Client, error) {
return NewClientWithURL(apiKey, "https://api.civo.com", region)
}
// NewAdvancedClientForTesting initializes a Client connecting to a local test server and allows for specifying methods
func NewAdvancedClientForTesting(responses map[string]map[string]string) (*Client, *httptest.Server, error) {
var responseSent bool
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
body, err := ioutil.ReadAll(req.Body)
if err != nil {
log.Printf("Error reading body: %v", err)
return
}
req.Body = ioutil.NopCloser(bytes.NewBuffer(body))
for url, criteria := range responses {
if strings.Contains(req.URL.String(), url) &&
req.Method == criteria["method"] {
if criteria["method"] == "PUT" || criteria["method"] == "POST" || criteria["method"] == "PATCH" {
if strings.TrimSpace(string(body)) == strings.TrimSpace(criteria["requestBody"]) {
responseSent = true
rw.Write([]byte(criteria["responseBody"]))
}
} else {
responseSent = true
rw.Write([]byte(criteria["responseBody"]))
}
}
}
if !responseSent {
fmt.Println("Failed to find a matching request!")
fmt.Println("Request body:", string(body))
fmt.Println("Method:", req.Method)
fmt.Println("URL:", req.URL.String())
rw.Write([]byte(`{"result": "failed to find a matching request"}`))
}
}))
client, err := NewClientForTestingWithServer(server)
return client, server, err
}
// NewClientForTesting initializes a Client connecting to a local test server
func NewClientForTesting(responses map[string]string) (*Client, *httptest.Server, error) {
var responseSent bool
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
for url, response := range responses {
if strings.Contains(req.URL.String(), url) {
responseSent = true
rw.Write([]byte(response))
}
}
if !responseSent {
fmt.Println("Failed to find a matching request!")
fmt.Println("URL:", req.URL.String())
rw.Write([]byte(`{"result": "failed to find a matching request"}`))
}
}))
client, err := NewClientForTestingWithServer(server)
return client, server, err
}
// NewClientForTestingWithServer initializes a Client connecting to a passed-in local test server
func NewClientForTestingWithServer(server *httptest.Server) (*Client, error) {
client, err := NewClientWithURL("TEST-API-KEY", server.URL, "TEST")
if err != nil {
return nil, err
}
client.httpClient = server.Client()
return client, err
}
func (c *Client) prepareClientURL(requestURL string) *url.URL {
u, _ := url.Parse(c.BaseURL.String() + requestURL)
return u
}
func (c *Client) sendRequest(req *http.Request) ([]byte, error) {
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", c.UserAgent)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("bearer %s", c.APIKey))
if req.Method == "GET" || req.Method == "DELETE" {
// add the region param
param := req.URL.Query()
param.Add("region", c.Region)
req.URL.RawQuery = param.Encode()
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
c.LastJSONResponse = string(body)
if resp.StatusCode >= 300 {
return nil, HTTPError{Code: resp.StatusCode, Status: resp.Status, Reason: string(body)}
}
return body, err
}
// SendGetRequest sends a correctly authenticated get request to the API server
func (c *Client) SendGetRequest(requestURL string) ([]byte, error) {
u := c.prepareClientURL(requestURL)
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return nil, err
}
return c.sendRequest(req)
}
// SendPostRequest sends a correctly authenticated post request to the API server
func (c *Client) SendPostRequest(requestURL string, params interface{}) ([]byte, error) {
u := c.prepareClientURL(requestURL)
// we create a new buffer and encode everything to json to send it in the request
jsonValue, _ := json.Marshal(params)
req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(jsonValue))
if err != nil {
return nil, err
}
return c.sendRequest(req)
}
// SendPutRequest sends a correctly authenticated put request to the API server
func (c *Client) SendPutRequest(requestURL string, params interface{}) ([]byte, error) {
u := c.prepareClientURL(requestURL)
// we create a new buffer and encode everything to json to send it in the request
jsonValue, _ := json.Marshal(params)
req, err := http.NewRequest("PUT", u.String(), bytes.NewBuffer(jsonValue))
if err != nil {
return nil, err
}
return c.sendRequest(req)
}
// SendDeleteRequest sends a correctly authenticated delete request to the API server
func (c *Client) SendDeleteRequest(requestURL string) ([]byte, error) {
u := c.prepareClientURL(requestURL)
req, err := http.NewRequest("DELETE", u.String(), nil)
if err != nil {
return nil, err
}
return c.sendRequest(req)
}
// DecodeSimpleResponse parses a response body in to a SimpleResponse object
func (c *Client) DecodeSimpleResponse(resp []byte) (*SimpleResponse, error) {
response := SimpleResponse{}
err := json.NewDecoder(bytes.NewReader(resp)).Decode(&response)
return &response, err
}