-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkatapult.go
179 lines (149 loc) · 3.26 KB
/
katapult.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
package katapult
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"time"
)
const (
DefaultUserAgent = "go-katapult"
DefaultTimeout = time.Second * 60
)
var DefaultURL = &url.URL{Scheme: "https", Host: "api.katapult.io"}
type Option func(c *Client) error
func WithHTTPClient(hc HTTPClient) Option {
return func(c *Client) error {
c.HTTPClient = hc
return nil
}
}
func WithUserAgent(ua string) Option {
return func(c *Client) error {
c.UserAgent = ua
return nil
}
}
func WithBaseURL(u *url.URL) Option {
return func(c *Client) error {
switch {
case u == nil:
return fmt.Errorf("katapult: base URL cannot be nil")
case u.Scheme == "":
return fmt.Errorf("katapult: base URL scheme is empty")
case u.Host == "":
return fmt.Errorf("katapult: base URL host is empty")
}
c.BaseURL = u
return nil
}
}
func WithAPIKey(key string) Option {
return func(c *Client) error {
c.APIKey = key
return nil
}
}
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}
type Client struct {
HTTPClient HTTPClient
APIKey string
UserAgent string
BaseURL *url.URL
}
func New(opts ...Option) (*Client, error) {
// Define default values for client
c := &Client{
HTTPClient: &http.Client{Timeout: DefaultTimeout},
BaseURL: DefaultURL,
UserAgent: DefaultUserAgent,
}
// Apply options to created Client
for _, o := range opts {
err := o(c)
if err != nil {
return nil, err
}
}
return c, nil
}
func (c *Client) Do(
ctx context.Context,
request *Request,
v interface{},
) (*Response, error) {
contentType, bodyReader, err := request.bodyContent()
if err != nil {
return nil, err
}
u := c.BaseURL.ResolveReference(request.URL)
req, err := http.NewRequestWithContext(
ctx, request.Method, u.String(), bodyReader,
)
if err != nil {
return nil, err
}
if len(request.Header) > 0 {
for k := range request.Header {
for _, v := range request.Header.Values(k) {
req.Header.Add(k, v)
}
}
}
if !request.NoAuth {
if c.APIKey == "" {
return nil, fmt.Errorf(
"%w: no API key available for authenticated request: %s %s",
ErrRequest, request.Method, request.URL.Path,
)
}
req.Header.Set(
"Authorization",
fmt.Sprintf("Bearer %s", c.APIKey),
)
}
req.Header.Set("User-Agent", c.UserAgent)
req.Header.Set("Accept", "application/json")
if contentType != "" {
req.Header.Set("Content-Type", contentType)
}
r, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer r.Body.Close()
resp := NewResponse(r)
if resp.StatusCode/100 != 2 {
return c.handleResponseError(resp)
}
if v != nil && resp.StatusCode != 204 {
if w, ok := v.(io.Writer); ok {
_, err = io.Copy(w, r.Body)
} else {
err = json.NewDecoder(resp.Body).Decode(v)
}
}
return resp, err
}
func (c *Client) handleResponseError(resp *Response) (*Response, error) {
var body responseErrorBody
err := json.NewDecoder(resp.Body).Decode(&body)
if err != nil {
return resp, ErrUnexpectedResponse
}
if body.Error == nil || body.Error.Code == "" {
return resp, ErrUnexpectedResponse
}
resp.Error = body.Error
respErr := NewResponseError(
resp.StatusCode,
body.Error.Code,
body.Error.Description,
body.Error.Detail,
)
return resp, castResponseError(respErr)
}