forked from ohookins/contentful-go
-
Notifications
You must be signed in to change notification settings - Fork 3
/
contentful.go
291 lines (250 loc) · 6.55 KB
/
contentful.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
286
287
288
289
290
291
package contentful
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httputil"
"net/url"
"path"
"strconv"
"strings"
"time"
"github.com/aoliveti/curling"
)
// Contentful model
type Contentful struct {
client *http.Client
api string
token string
Debug bool
QueryParams map[string]string
Headers map[string]string
BaseURL string
UploadURL string
Environment string
Spaces *SpacesService
APIKeys *APIKeyService
Assets *AssetsService
ContentTypes *ContentTypesService
Entries *EntriesService
Locales *LocalesService
Tags *TagsService
Upload *UploadService
Webhooks *WebhooksService
}
type service struct {
c *Contentful
}
func getEnvPath(c *Contentful) string {
if c.Environment != "" {
return fmt.Sprintf("/environments/%s", c.Environment)
}
return ""
}
// NewCMA returns a CMA client
func NewCMA(token string) *Contentful {
c := &Contentful{
client: http.DefaultClient,
api: "CMA",
token: token,
Debug: false,
Headers: map[string]string{
"Authorization": fmt.Sprintf("Bearer %s", token),
"Content-Type": "application/vnd.contentful.management.v1+json",
"X-Contentful-User-Agent": fmt.Sprintf("sdk contentful.go/%s", Version),
},
BaseURL: "https://api.contentful.com",
UploadURL: "https://upload.contentful.com",
}
c.Spaces = &SpacesService{c: c}
c.APIKeys = &APIKeyService{c: c}
c.Assets = &AssetsService{c: c}
c.ContentTypes = &ContentTypesService{c: c}
c.Entries = &EntriesService{c: c}
c.Tags = &TagsService{c: c}
c.Upload = &UploadService{c: c}
c.Locales = &LocalesService{c: c}
c.Webhooks = &WebhooksService{c: c}
return c
}
// NewCDA returns a CDA client
func NewCDA(token string) *Contentful {
c := &Contentful{
client: http.DefaultClient,
api: "CDA",
token: token,
Debug: false,
Headers: map[string]string{
"Authorization": "Bearer " + token,
"Content-Type": "application/vnd.contentful.delivery.v1+json",
"X-Contentful-User-Agent": fmt.Sprintf("contentful-go/%s", Version),
},
BaseURL: "https://cdn.contentful.com",
}
c.Spaces = &SpacesService{c: c}
c.APIKeys = &APIKeyService{c: c}
c.Assets = &AssetsService{c: c}
c.ContentTypes = &ContentTypesService{c: c}
c.Entries = &EntriesService{c: c}
c.Tags = &TagsService{c: c}
c.Locales = &LocalesService{c: c}
c.Webhooks = &WebhooksService{c: c}
return c
}
// NewCPA returns a CPA client
func NewCPA(token string) *Contentful {
c := &Contentful{
client: http.DefaultClient,
Debug: false,
api: "CPA",
token: token,
Headers: map[string]string{
"Authorization": "Bearer " + token,
},
BaseURL: "https://preview.contentful.com",
}
c.Spaces = &SpacesService{c: c}
c.APIKeys = &APIKeyService{c: c}
c.Assets = &AssetsService{c: c}
c.ContentTypes = &ContentTypesService{c: c}
c.Entries = &EntriesService{c: c}
c.Tags = &TagsService{c: c}
c.Locales = &LocalesService{c: c}
c.Webhooks = &WebhooksService{c: c}
return c
}
// SetOrganization sets the given organization id
func (c *Contentful) SetOrganization(organizationID string) *Contentful {
c.Headers["X-Contentful-Organization"] = organizationID
return c
}
// SetHTTPClient sets the underlying http.Client used to make requests.
func (c *Contentful) SetHTTPClient(client *http.Client) *Contentful {
c.client = client
return c
}
// SetHTTPTransport creates a new http.Client and sets a custom Roundtripper.
func (c *Contentful) SetHTTPTransport(t http.RoundTripper) *Contentful {
c.client = &http.Client{
Transport: t,
}
return c
}
// SetBaseURL provides an option to change the BaseURL of the client
func (c *Contentful) SetBaseURL(baseURL string) *Contentful {
c.BaseURL = baseURL
return c
}
func (c *Contentful) newRequest(ctx context.Context, method, requestPath string, query url.Values, body io.Reader, additionalHeaders map[string]string) (*http.Request, error) {
if idx := strings.Index(requestPath, "?"); idx != -1 {
requestPath = requestPath[:idx]
}
cleanUrl := path.Clean(requestPath)
_, lastSegment := path.Split(cleanUrl)
var u *url.URL
var err error
switch lastSegment {
case "uploads":
u, err = url.Parse(c.UploadURL)
default:
u, err = url.Parse(c.BaseURL)
}
if err != nil {
return nil, err
}
// set query params
for key, value := range c.QueryParams {
query.Set(key, value)
}
u.Path = u.Path + requestPath
u.RawQuery = query.Encode()
req, err := http.NewRequestWithContext(ctx, method, u.String(), body)
if err != nil {
return nil, err
}
// set headers
for key, value := range c.Headers {
req.Header.Set(key, value)
}
for key, value := range additionalHeaders {
req.Header.Set(key, value)
}
return req, nil
}
func (c *Contentful) do(req *http.Request, v interface{}) error {
if c.Debug {
if cmd, err := curling.NewFromRequest(req); err == nil {
fmt.Println(cmd)
}
}
res, err := c.client.Do(req)
if err != nil {
return err
}
if res.StatusCode >= 200 && res.StatusCode < 400 {
if v != nil {
defer res.Body.Close()
err = json.NewDecoder(res.Body).Decode(v)
if err != nil {
return err
}
}
return nil
}
// parse api response
apiError := c.handleError(req, res)
// return apiError if it is not rate limit error
var rateLimitExceededError RateLimitExceededError
if !errors.As(apiError, &rateLimitExceededError) {
return apiError
}
resetHeader := res.Header.Get("x-contentful-ratelimit-reset")
// return apiError if Ratelimit-Reset header is not presented
if resetHeader == "" {
return apiError
}
// wait X-Contentful-Ratelimit-Reset amount of seconds
waitSeconds, err := strconv.Atoi(resetHeader)
if err != nil {
return apiError
}
time.Sleep(time.Second * time.Duration(waitSeconds))
return c.do(req, v)
}
func (c *Contentful) handleError(req *http.Request, res *http.Response) error {
if c.Debug {
if dump, err := httputil.DumpResponse(res, true); err == nil {
fmt.Printf("%q", dump)
}
}
var e ErrorResponse
defer res.Body.Close()
err := json.NewDecoder(res.Body).Decode(&e)
if err != nil {
return err
}
apiError := APIError{
req: req,
res: res,
err: &e,
}
switch errType := e.Sys.ID; errType {
case "NotFound":
return NotFoundError{apiError}
case "RateLimitExceeded":
return RateLimitExceededError{apiError}
case "AccessTokenInvalid":
return AccessTokenInvalidError{apiError}
case "ValidationFailed", "UnresolvedLinks":
return ValidationFailedError{apiError}
case "VersionMismatch":
return VersionMismatchError{apiError}
case "Conflict":
return VersionMismatchError{apiError}
default:
return e
}
}