-
Notifications
You must be signed in to change notification settings - Fork 17
/
client.go
230 lines (201 loc) · 6.13 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
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
package easypost
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"github.com/google/go-querystring/query"
"github.com/google/uuid"
"io"
"io/ioutil"
"net/http"
"net/url"
"runtime"
"time"
)
var apiBaseURL = &url.URL{
Scheme: "https", Host: "api.easypost.com", Path: "/v2/",
}
var defaultUserAgent string
var defaultTimeout int
func init() {
// We skip grabbing the OS version (for now) as there is not a reliable way to do so across OS's
defaultUserAgent = fmt.Sprintf(
"EasyPost/v2 GoClient/%s Go/%s OS/%s OSVersion/%s OSArch/%s",
Version, runtime.Version(), runtime.GOOS, "NA", runtime.GOARCH)
defaultTimeout = 60000
}
// A Client provides an HTTP client for EasyPost API operations.
type Client struct {
// BaseURL specifies the location of the API. It is used with
// ResolveReference to create request URLs. (If 'Path' is specified, it
// should end with a trailing slash.) If nil, the default will be used.
BaseURL *url.URL
// Client is an HTTP client used to make API requests. If nil,
// http.DefaultClient will be used.
Client *http.Client
// APIKey is the user's API key. It is required.
// Note: Treat your API Keys as passwords—keep them secret. API Keys give
// full read/write access to your account, so they should not be included in
// public repositories, emails, client side code, etc.
APIKey string
// UserAgent is a User-Agent to be sent with API HTTP requests. If empty,
// a default will be used.
UserAgent string
// Timeout specifies the time limit (in milliseconds) for requests made by this Client. The
// timeout includes connection time, any redirects, and reading the
// response body.
Timeout int
// MockRequests is a list of requests that will be mocked by the client.
MockRequests []MockRequest
// Hooks is a collection of HookEventSubscriber instances for various hooks available in the client
Hooks Hooks
}
// New returns a new Client with the given API key.
func New(apiKey string) *Client {
return &Client{APIKey: apiKey}
}
func (c *Client) baseURL() *url.URL {
if c.BaseURL != nil {
return c.BaseURL
}
return apiBaseURL
}
func (c *Client) userAgent() string {
if c.UserAgent != "" {
return c.UserAgent
}
return defaultUserAgent
}
func (c *Client) timeout() time.Duration {
// return timeout duration in milliseconds
timeout := c.Timeout
if c.Timeout <= 0 {
timeout = defaultTimeout
}
return time.Duration(timeout) * time.Millisecond
}
func (c *Client) client() *http.Client {
client := c.Client
if client == nil {
client = http.DefaultClient
}
client.Timeout = c.timeout()
return client
}
func (c *Client) setParameters(req *http.Request, params interface{}) error {
switch req.Method {
case http.MethodGet, http.MethodDelete:
// Convert interface into query parameters and set as request URL query
values, _ := query.Values(params)
req.URL.RawQuery = values.Encode()
return nil
case http.MethodPost, http.MethodPut, http.MethodPatch:
// Convert interface into JSON and set as request body
buf, err := json.Marshal(params)
if err != nil {
return err
}
req.Body = ioutil.NopCloser(bytes.NewReader(buf))
req.GetBody = func() (io.ReadCloser, error) {
return ioutil.NopCloser(bytes.NewReader(buf)), nil
}
req.Header.Set("Content-Type", "application/json")
// Setting Content-Length avoids chunked encoding, which the API
// server doesn't currently support.
req.ContentLength = int64(len(buf))
return nil
default:
return fmt.Errorf("unsupported method: %s", req.Method)
}
}
func (c *Client) do(ctx context.Context, method, path string, params interface{}, out interface{}) error {
if c.APIKey == "" {
return newMissingPropertyError("APIKey")
}
req := &http.Request{
Method: method,
URL: c.baseURL().ResolveReference(&url.URL{Path: path}),
Header: make(http.Header, 2),
}
req.Header.Set("User-Agent", c.userAgent())
if err := c.setParameters(req, params); err != nil {
return err
}
req.SetBasicAuth(c.APIKey, "")
if ctx != nil {
req = req.WithContext(ctx)
}
var res *http.Response
var err error
// prepare and execute request hook(s)
requestId := uuid.New()
requestTimestamp := time.Now()
requestEvent := &RequestHookEvent{
Method: req.Method,
Url: req.URL,
RequestBody: req.Body,
Headers: req.Header,
RequestTimestamp: requestTimestamp,
Id: requestId,
}
// loop over each request hook and execute it
for _, hook := range c.Hooks.RequestHookEventSubscriptions {
hook.Execute(ctx, *requestEvent)
}
if len(c.MockRequests) > 0 {
// If there are mock requests set, this client will ONLY make mock requests
res = c.findMatchingMockRequest(req)
if res == nil {
return errors.New("no matching mock request found")
}
} else {
// Otherwise, make a real request
res, err = c.client().Do(req)
}
if err != nil {
// prepare and execute response hook(s) for failed requests
responseEvent := &ResponseHookEvent{
HttpStatus: 0,
Method: req.Method,
Url: req.URL,
ResponseBody: nil,
Headers: nil,
RequestTimestamp: requestTimestamp,
ResponseTimestamp: time.Now(),
Id: requestId,
}
// loop over each response hook and execute it
for _, hook := range c.Hooks.ResponseHookEventSubscriptions {
hook.Execute(ctx, *responseEvent)
}
return err
}
// prepare and execute response hook(s) for successful requests
responseEvent := &ResponseHookEvent{
HttpStatus: res.StatusCode,
Method: req.Method,
Url: req.URL,
ResponseBody: res.Body,
Headers: res.Header,
RequestTimestamp: requestTimestamp,
ResponseTimestamp: time.Now(),
Id: requestId,
}
// loop over each response hook and execute it
for _, hook := range c.Hooks.ResponseHookEventSubscriptions {
hook.Execute(ctx, *responseEvent)
}
defer func() { _ = res.Body.Close() }()
// status code is 2xx, no error occurred
if res.StatusCode >= 200 && res.StatusCode <= 299 {
if out != nil {
return json.NewDecoder(res.Body).Decode(out)
}
return nil
}
// status code is not 2xx, an error occurred
apiErr := BuildErrorFromResponse(res)
return apiErr
}