forked from lukemilby/lichess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
65 lines (58 loc) · 1.33 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
package lichess
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
)
// HTTPClient interface
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}
type Client struct {
BaseURL *url.URL
UserAgent string
APIKey string
HttpClient HTTPClient
}
func (c *Client) newRequest(method, path string, body interface{}) (*http.Request, error) {
if c.BaseURL == nil {
return nil, errors.New("BaseURL is undefined")
}
if c.APIKey == "" {
return nil, errors.New("APIKey is undefined")
}
rel := &url.URL{Path: path}
u := c.BaseURL.ResolveReference(rel)
var buf io.ReadWriter
if body != nil {
buf = new(bytes.Buffer)
err := json.NewEncoder(buf).Encode(body)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, u.String(), buf)
if err != nil {
return nil, err
}
// Default request is json
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", c.UserAgent)
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.APIKey))
return req, nil
}
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()
err = json.NewDecoder(resp.Body).Decode(v)
return resp, err
}