-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
100 lines (76 loc) · 1.72 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
package ves
import (
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
type Client struct {
BaseURL string
Key string
Version int
httpClient *http.Client
Vehicles *VehiclesService
}
type OptFunc func(c *Client)
func NewClient(opts ...OptFunc) *Client {
c := &Client{
BaseURL: VESAPIUrl,
Version: VESAPIVersion,
httpClient: &http.Client{
Timeout: time.Second * 5,
},
}
for _, f := range opts {
f(c)
}
c.Vehicles = newVehiclesService(c)
return c
}
func (c *Client) do(req *http.Request, v interface{}) (*http.Response, error) {
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusBadRequest {
return nil, fmt.Errorf("%s", resp.Body)
}
return resp, json.NewDecoder(resp.Body).Decode(v)
}
func (c *Client) NewRequest(method string, path string, body io.Reader) *Request {
url := fmt.Sprintf("%s/v%d/%s", c.BaseURL, c.Version, path)
req, err := http.NewRequest(method, url, body)
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-api-key", c.Key)
return &Request{req, c, err}
}
type Request struct {
*http.Request
c *Client
e error
}
func (r *Request) Do(v interface{}) (*http.Response, error) {
if r.e != nil {
return nil, r.e
}
resp, err := r.c.httpClient.Do(r.Request)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
var errResp ErrorResponse
err := json.NewDecoder(resp.Body).Decode(&errResp)
if err != nil {
return resp, err
}
return resp, errResp.Errors[0]
}
if v != nil {
return resp, json.NewDecoder(resp.Body).Decode(v)
}
return resp, nil
}