-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathclient.go
285 lines (237 loc) · 7.56 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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package sanity
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"regexp"
"runtime"
"time"
"github.com/jpillora/backoff"
"github.com/sanity-io/client-go/internal/requests"
)
const (
// Default dataset name for sanity projects
DefaultDataset = "production"
// API Host for skipping CDN
APIHost = "api.sanity.io"
// API Host which connects through CDN
APICDNHost = "apicdn.sanity.io"
// VersionV1 is API version 1, the initial released version
VersionV1 = Version("1")
// VersionExperimental is the experimental API version
VersionExperimental = Version("X")
// Latest API version release
VersionV20210325 = Version("2021-03-25")
// Deprecated: VersionDefault is the API version used when client is
// instantiated without any specific version.
VersionDefault = VersionV1
)
// Version is an API version, generally be dates in ISO format but also
// "1" (for backwards compatibility) and "X" (for experimental features)
type Version string
// String implements fmt.Stringer.
func (version Version) String() string {
return string(version)
}
// Validate validates a version
func (version Version) Validate() error {
if version == "" {
return errors.New("no version given")
}
regExpVersion := regexp.MustCompile(`^(1|X|\d{4}-\d{2}-\d{2})$`)
if !regExpVersion.MatchString(string(version)) {
return fmt.Errorf("invalid version format %q", version)
}
return nil
}
// Client implements a client for interacting with the Sanity API.
type Client struct {
hc *http.Client
apiVersion Version
useCDN bool
baseAPIURL url.URL
baseQueryURL url.URL // if useCDN=false, baseQueryURL will be same as baseAPIURL.
customHeaders http.Header
token string
projectID string
dataset string
backoff backoff.Backoff
callbacks Callbacks
setHeaders func(r *requests.Request)
tag string
}
type Option func(c *Client)
// WithHTTPClient returns an option for setting a custom HTTP client.
func WithHTTPClient(client *http.Client) Option {
return func(c *Client) { c.hc = client }
}
// WithCallbacks returns an option that enables callbacks for common events
// such as errors.
func WithCallbacks(cbs Callbacks) Option {
return func(c *Client) { c.callbacks = cbs }
}
// WithBackoff returns an option that configures network request backoff. For how
// backoff works, see the underlying backoff package: https://github.com/jpillora/backoff.
// By default, the client uses the backoff package's default (maximum 10 seconds wait,
// backoff factor of 2).
func WithBackoff(b backoff.Backoff) Option {
return func(c *Client) { c.backoff = b }
}
// WithToken returns an option that sets the API token to use.
func WithToken(t string) Option {
return func(c *Client) { c.token = t }
}
// WithCDN returns an option that enables or disables the use of the Sanity API CDN.
// It is ignored when a custom HTTP host is set.
func WithCDN(b bool) Option {
return func(c *Client) { c.useCDN = b }
}
// WithHTTPHost returns an option that changes the API URL.
func WithHTTPHost(scheme, host string) Option {
return func(c *Client) {
c.baseAPIURL.Scheme = scheme
c.baseAPIURL.Host = host
c.baseQueryURL.Scheme = scheme
c.baseQueryURL.Host = host
}
}
// WithHTTPHeader returns an option for setting a custom HTTP header.
// These headers are set in addition to the ones defined in Client.setHeaders().
// If a custom header is added with the same key as one of default header, then
// custom value is appended to key, and does not replace default value.
func WithHTTPHeader(key, value string) Option {
return func(c *Client) {
if c.customHeaders == nil {
c.customHeaders = make(http.Header)
}
c.customHeaders.Add(key, value)
}
}
// WithTag returns an option for setting the default tag to set on all requests.
func WithTag(t string) Option {
return func(c *Client) { c.tag = t }
}
// Deprecated: Use version.NewClient() instead.
// New returns a new client with a default API version. A project ID must be provided.
// Zero or more options can be passed. For example:
//
// client := sanity.New("projectId", sanity.DefaultDataset,
// sanity.WithCDN(true), sanity.WithToken("mytoken"))
func New(projectID, dataset string, opts ...Option) (*Client, error) {
return VersionDefault.NewClient(projectID, dataset, opts...)
}
// NewClient returns a new versioned client. A project ID must be provided.
// Zero or more options can be passed. For example:
//
// client := sanity.VersionV20210325.NewClient("projectId", sanity.DefaultDataset,
// sanity.WithCDN(true), sanity.WithToken("mytoken"))
//
func (v Version) NewClient(projectID, dataset string, opts ...Option) (*Client, error) {
if projectID == "" {
return nil, errors.New("project ID cannot be empty")
}
if dataset == "" {
return nil, errors.New("dataset must be set")
}
baseAPIURL := fmt.Sprintf("%s.%s", projectID, APIHost)
c := Client{
backoff: backoff.Backoff{Jitter: true},
hc: http.DefaultClient,
projectID: projectID,
dataset: dataset,
apiVersion: v,
baseAPIURL: url.URL{
Scheme: "https",
Host: baseAPIURL,
Path: fmt.Sprintf("/v%s", v.String()),
},
}
for _, opt := range opts {
opt(&c)
}
c.baseQueryURL = c.baseAPIURL
// Only use APICDN if useCDN=true and API host has not been updated by options.
if c.useCDN && c.baseAPIURL.Host == baseAPIURL {
c.baseQueryURL.Host = fmt.Sprintf("%s.%s", projectID, APICDNHost)
}
setDefaultHeaders := func(r *requests.Request) {
r.Header("user-agent", "Sanity Go client/"+runtime.Version())
if c.token != "" {
r.Header("authorization", "Bearer "+c.token)
}
}
c.setHeaders = func(r *requests.Request) {
setDefaultHeaders(r)
for key, values := range c.customHeaders {
for _, value := range values {
r.Header(key, value)
}
}
}
return &c, nil
}
func (c *Client) do(ctx context.Context, r *requests.Request, dest interface{}) (*http.Response, error) {
req, err := r.HTTPRequest()
if err != nil {
return nil, err
}
// Workaround for setting custom host header which is overridden after req.Header.Add()
// See: https://github.com/golang/go/issues/29865
if host := req.Header.Get("host"); host != "" {
req.Host = host
}
if req.Method == http.MethodGet && len(r.EncodeURL()) > maxGETRequestURLLength {
return nil, errors.New("max URL length exceeded in GET request")
}
req = req.WithContext(ctx)
bckoff := c.backoff
for {
resp, err := c.hc.Do(req)
if err != nil {
return nil, fmt.Errorf("[%s %s] failed: %w", req.Method, req.URL.String(), err)
}
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode >= 200 && resp.StatusCode <= 299 {
return resp, json.NewDecoder(resp.Body).Decode(dest)
}
if !isMethodRetriable(req.Method) || !isStatusCodeRetriable(resp.StatusCode) {
return nil, c.handleErrorResponse(req, resp)
}
_ = resp.Body.Close()
if c.callbacks.OnErrorWillRetry != nil {
c.callbacks.OnErrorWillRetry(err)
}
time.Sleep(bckoff.Duration())
}
}
func (c *Client) handleErrorResponse(req *http.Request, resp *http.Response) error {
body := []byte("[no response body]")
if resp.Body != nil {
var err error
if body, err = ioutil.ReadAll(resp.Body); err != nil {
body = []byte(fmt.Sprintf("[failed to read response body: %s]", err))
}
}
return &RequestError{
Request: req,
Response: resp,
Body: body,
}
}
func (c *Client) newAPIRequest() *requests.Request {
r := requests.New(c.baseAPIURL)
c.setHeaders(r)
return r
}
func (c *Client) newQueryRequest() *requests.Request {
r := requests.New(c.baseQueryURL)
c.setHeaders(r)
return r
}
const maxGETRequestURLLength = 1024