-
Notifications
You must be signed in to change notification settings - Fork 1
/
tapas.go
83 lines (71 loc) · 2.2 KB
/
tapas.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
// Package tapas is a client for Tapas API at api.tapas.io.
package tapas
import (
"encoding/json"
"net/http"
"net/url"
"github.com/pkg/errors"
)
// Client implements a way to talk to Tapas' API.
type Client struct {
base, path string
client *http.Client
deviceType, deviceUUID string
}
// An OptionFunc can be used to modify the client.
type OptionFunc func(*Client)
// WithBase sets the API base.
func WithBase(base string) OptionFunc {
return func(c *Client) { c.base = base }
}
// WithPath replaces the default path. Might be used on a new API version.
func WithPath(path string) OptionFunc {
return func(c *Client) { c.path = path }
}
// WithDeviceType sets the device type. Defaults to "ANDROID".
func WithDeviceType(deviceType string) OptionFunc {
return func(c *Client) { c.deviceType = deviceType }
}
// WithDeviceUUID sets the device UUID. Defaults to an empty string, please use
// 16 character long hex string if needed.
func WithDeviceUUID(deviceUUID string) OptionFunc {
return func(c *Client) { c.deviceUUID = deviceUUID }
}
// WithHTTPClient makes the manga client use a given http.Client to make
// requests.
func WithHTTPClient(client *http.Client) OptionFunc {
return func(c *Client) { c.client = client }
}
// New returns a new Tapas Client.
func New(options ...OptionFunc) *Client {
c := &Client{
base: "https://api.tapas.io",
path: "/v3",
client: http.DefaultClient,
}
for _, option := range options {
option(c)
}
return c
}
// get sends a HTTP GET request.
func (c *Client) get(endpoint string, query url.Values) (json.RawMessage, error) {
req, err := http.NewRequest(http.MethodGet, c.base+c.path+endpoint, nil)
if err != nil {
return nil, errors.Wrap(err, "could not create get request")
}
req.URL.RawQuery = query.Encode()
req.Header.Add("accept", "application/panda+json")
req.Header.Add("x-device-type", c.deviceType)
req.Header.Add("x-device-uuid", c.deviceUUID)
res, err := c.client.Do(req)
if err != nil {
return nil, errors.Wrapf(err, "could not get %s", req.URL)
}
defer res.Body.Close()
var raw json.RawMessage
if err := json.NewDecoder(res.Body).Decode(&raw); err != nil {
return nil, errors.Wrap(err, "could not decode response")
}
return raw, nil
}