-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
100 lines (85 loc) · 2.04 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 okapi
import (
"bytes"
"fmt"
"io"
"net/http"
"net/url"
)
// Client provides the Okapi API client which should be embedded in your client
// objects.
type Client struct {
httpClient *http.Client
config Config
}
// NewClient returns a new Okapi client with a default httpClient.
func NewClient(config *Config) (*Client, error) {
httpClient := &http.Client{}
client := &Client{
config: *config,
httpClient: httpClient,
}
return client, nil
}
// newRequest creates a new request object.
func (c *Client) newRequest(method, path string) (*request, error) {
base, err := url.Parse(c.config.Address)
if err != nil {
return nil, err
}
u, err := url.Parse(path)
if err != nil {
return nil, err
}
r := &request{
config: &c.config,
method: method,
url: &url.URL{
Scheme: base.Scheme,
User: base.User,
Host: base.Host,
Path: u.Path,
RawPath: u.RawPath,
},
params: make(map[string][]string),
}
if c.config.WaitTime != 0 {
r.params.Set("wait", r.config.WaitTime.String())
}
for key, values := range u.Query() {
for _, value := range values {
r.params.Add(key, value)
}
}
return r, nil
}
// do builds an http.Request, converts the request object to a standard
// http.Request, and performs the get query itself. The response body is decoded
// into the QueryOptions Out interface. It raises an error if the reponse status
// code is anything but 200.
func (c *Client) do(method, endpoint string, q *QueryOptions) (*http.Response, error) {
req, err := c.newRequest(method, endpoint)
if err != nil {
return nil, err
}
http, err := req.withQueryOptions(q).toHTTP()
if err != nil {
return nil, err
}
resp, err := c.httpClient.Do(http)
if err != nil {
return resp, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
var buf bytes.Buffer
io.Copy(&buf, resp.Body)
return resp, fmt.Errorf("Unexpected response code: %d (%s)", resp.StatusCode, buf.String())
}
if q.Out != nil {
if err := decodeBody(resp, &q.Out); err != nil {
return resp, err
}
}
return resp, nil
}