forked from chargehound/chargehound-go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequestor.go
More file actions
77 lines (62 loc) · 1.54 KB
/
requestor.go
File metadata and controls
77 lines (62 loc) · 1.54 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
package chargehound
import (
"encoding/json"
"io"
"net/http"
"net/url"
)
type apiRequestor struct {
APIKey string
APIVersion string
userAgent string
bodyJSON io.Reader
httpClient *http.Client
method string
queryParams *url.Values
url string
}
func newAPIRequestor(cc *Client, optHTTP *http.Client, method, path string, bodyJSON io.Reader, queryParams *url.Values) (*apiRequestor, error) {
var HTTPClient *http.Client
if optHTTP != nil {
HTTPClient = optHTTP
} else {
HTTPClient = cc.HTTPClient
}
url := cc.Protocol + cc.Host + cc.Basepath + path
if queryParams != nil {
url += "?" + queryParams.Encode()
}
requestor := apiRequestor{
APIKey: cc.APIKey,
APIVersion: cc.APIVersion,
bodyJSON: bodyJSON,
httpClient: HTTPClient,
method: method,
queryParams: queryParams,
url: url,
userAgent: "Chargehound/v1 GoBindings/" + cc.Version,
}
return &requestor, nil
}
func (ar *apiRequestor) newRequest(v interface{}) (*http.Response, error) {
req, err := http.NewRequest(ar.method, ar.url, ar.bodyJSON)
if err != nil {
return nil, err
}
req.SetBasicAuth(ar.APIKey, "")
req.Header.Add("User-Agent", ar.userAgent)
req.Header.Add("Content-Type", "application/json")
if ar.APIVersion != "" {
req.Header.Add("Chargehound-Version", ar.APIVersion)
}
res, err := ar.httpClient.Do(req)
if err != nil {
return nil, err
}
if res.StatusCode >= 400 {
return nil, responseToError(res)
}
decoder := json.NewDecoder(res.Body)
err = decoder.Decode(&v)
return res, err
}