/
client.go
89 lines (71 loc) · 1.87 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
package wordnik
import (
"encoding/json"
"io"
"net/http"
"net/url"
"time"
)
const (
base = "https://api.wordnik.com/v4/"
)
// Client is an http.Client wrapper which stores an API key and base url.
type Client struct {
apiKey string
baseURL *url.URL
client *http.Client
}
// NewClient creates a Client with the specified API key. The http.Client
// component is configured with a 10-second timeout.
func NewClient(key string, customClients ...*http.Client) *Client {
baseURL, err := url.Parse(base)
if err != nil {
panic(err)
}
var httpClient *http.Client
if len(customClients) > 0 && customClients[0] != nil {
httpClient = customClients[0]
} else {
httpClient = &http.Client{Timeout: time.Second * 10}
}
return &Client{key, baseURL, httpClient}
}
func (c *Client) formRequest(relativePath *url.URL, vals url.Values, method string, reader ...io.Reader) (*http.Request, error) {
u := c.baseURL.ResolveReference(relativePath)
u.RawQuery = vals.Encode()
var body io.Reader
if len(reader) != 0 {
body = reader[0]
}
request, err := http.NewRequest(method, u.String(), body)
if err != nil {
return request, err
}
request.Header["api_key"] = []string{c.apiKey}
request.Header["Content-type"] = []string{"application/json"}
return request, nil
}
func (c *Client) doRequest(req *http.Request, dst interface{}) error {
res, err := c.client.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if dst == nil {
return nil
}
return json.NewDecoder(res.Body).Decode(dst)
}
// basicGetRequest is a helper method which makes most of the GET requests
// endpoints simpler.
func (c *Client) basicGetRequest(rel *url.URL, vals url.Values, dst interface{}, options ...QueryOption) error {
for _, option := range options {
option(&vals)
}
req, err := c.formRequest(rel, vals, "GET")
if err != nil {
return err
}
err = c.doRequest(req, dst)
return err
}