-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
521 lines (452 loc) · 13.8 KB
/
request.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
package pixaven
import (
"bytes"
"context"
"encoding/json"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"github.com/valyala/fastjson"
)
// Request is a generator that allows creation of Pixaven API requests.
type Request struct {
client *Client
http *http.Client
source source
reader io.Reader
location string
context context.Context
flip P
resize P
scale P
crop P
watermark P
mask P
stylize P
adjust P
auto P
border P
padding P
store P
output P
webhook P
response P
cdn P
}
// There are three sources of data:
// - a Reader source, when user passes an io.Reader to Upload()
// - a Path soruce, when user passes a path string to Upload()
// - a Fetch source, when user passes an URL to Fetch()
type source int
const (
readerSource source = iota
pathSource
fetchSource
)
// P is a short name for all hashes passed to the Pixaven API.
type P map[string]interface{}
// HTTPClient replaces the client used to execute the request.
func (r *Request) HTTPClient(client *http.Client) *Request {
r.http = client
return r
}
// Flip adds an image flipping step to the transformation flow.
// Check out Pixaven docs for more details.
func (r *Request) Flip(data P) *Request {
r.flip = data
return r
}
// Resize adds an image resizing step to the transformation flow.
// Check out Pixaven docs for more details.
func (r *Request) Resize(data P) *Request {
r.resize = data
return r
}
// Scale adds an image scaling step to the transformation flow.
// Check out Pixaven docs for more details.
func (r *Request) Scale(data P) *Request {
r.scale = data
return r
}
// Crop adds an image cropping step to the transformation flow.
// Check out Pixaven docs for more details.
func (r *Request) Crop(data P) *Request {
r.crop = data
return r
}
// Watermark adds a watermark application to the transformation flow.
// Check out Pixaven docs for more details.
func (r *Request) Watermark(data P) *Request {
r.watermark = data
return r
}
// Mask adds application of an elliptical mask to the transformation flow.
// Check out Pixaven docs for more details.
func (r *Request) Mask(data P) *Request {
r.mask = data
return r
}
// Stylize adds filter application to the transformation flow.
// Check out Pixaven docs for more details.
func (r *Request) Stylize(data P) *Request {
r.stylize = data
return r
}
// Adjust adds an visual parameters adjustment to the transformation flow.
// Check out Pixaven docs for more details.
func (r *Request) Adjust(data P) *Request {
r.adjust = data
return r
}
// Auto adds an automatic image enhancement step to the transformation flow.
// Check out Pixaven docs for more details.
func (r *Request) Auto(data P) *Request {
r.auto = data
return r
}
// Border adds adding a border to the image to the transformation flow.
// Check out Pixaven docs for more details.
func (r *Request) Border(data P) *Request {
r.border = data
return r
}
// Padding adds an image padding step to the transformation flow.
// Check out Pixaven docs for more details.
func (r *Request) Padding(data P) *Request {
r.padding = data
return r
}
// Store specifies where the image should be stored after transformations.
// Check out Pixaven docs for more details.
func (r *Request) Store(data P) *Request {
r.store = data
return r
}
// Output sets the output format and encoding.
// Check out Pixaven docs for more details.
func (r *Request) Output(data P) *Request {
r.output = data
return r
}
// Webhook sets a webhook as a response delivery method.
// Check out Pixaven docs for more details.
func (r *Request) Webhook(data P) *Request {
r.webhook = data
return r
}
// CDN configures CDN settings of the platform.
// Check out Pixaven docs for more details.
func (r *Request) CDN(data P) *Request {
r.cdn = data
return r
}
// Context sets the context of the HTTP request.
func (r *Request) Context(ctx context.Context) *Request {
r.context = ctx
return r
}
// Internal execution function of HTTP requests.
func (r *Request) execute() (*http.Response, error) {
// First use this hack to create a map with params
params := map[string]interface{}{}
if r.resize != nil {
params["resize"] = r.resize
}
if r.scale != nil {
params["scale"] = r.scale
}
if r.crop != nil {
params["crop"] = r.crop
}
if r.watermark != nil {
params["watermark"] = r.watermark
}
if r.mask != nil {
params["mask"] = r.mask
}
if r.stylize != nil {
params["stylize"] = r.stylize
}
if r.adjust != nil {
params["adjust"] = r.adjust
}
if r.auto != nil {
params["auto"] = r.auto
}
if r.border != nil {
params["border"] = r.border
}
if r.padding != nil {
params["padding"] = r.padding
}
if r.store != nil {
params["store"] = r.store
}
if r.output != nil {
params["output"] = r.output
}
if r.webhook != nil {
params["webhook"] = r.webhook
}
if r.response != nil {
params["response"] = r.response
}
if r.cdn != nil {
params["cdn"] = r.cdn
}
if r.source == fetchSource {
params["url"] = r.location
}
// Then encode it
pb, err := json.Marshal(params)
if err != nil {
return nil, err
}
// Decide on URL, Content-Type header and body dpeending on the source of the image.
var (
url string
contentType string
body io.Reader
)
if r.source == fetchSource {
// .Fetch(url) is straightforward
url = apiURL + "/fetch"
body = bytes.NewReader(pb)
contentType = "application/json"
} else if r.source == readerSource || r.source == pathSource {
// .Upload(<any>) has two cases
url = apiURL + "/upload"
var file io.Reader
if r.source == readerSource {
// .Upload(<io.Reader>) simply passes the stream further down the pipeline.
file = r.reader
} else if r.source == pathSource {
// .Upload(path) requires the file to be opened.
fs, err := os.OpenFile(r.location, os.O_RDONLY, 0600)
if err != nil {
return nil, err
}
defer fs.Close() // close it when the function ends
file = fs
}
// Prepare a buffer for the multipart body writer
buf := &bytes.Buffer{}
body = buf
writer := multipart.NewWriter(buf)
// Create the file upload part
part, err := writer.CreateFormFile("file", "")
if err != nil {
return nil, err
}
if _, err := io.Copy(part, file); err != nil {
return nil, err
}
// Insert the JSON data into a "data" field
if err := writer.WriteField("data", string(pb)); err != nil {
return nil, err
}
// End the writing
if err := writer.Close(); err != nil {
return nil, err
}
// Set the content type accordingly
contentType = writer.FormDataContentType()
} else {
// shouldn't happen
return nil, ErrInvalidSourceType
}
// Create a new HTTP request using previously computed data.
request, err := http.NewRequest("POST", url, body)
if err != nil {
return nil, err
}
// Apply headers - Content-Type, Binary and Authorization
request.Header.Set("Content-Type", contentType)
// Set the context of the request
if r.context != nil {
request = request.WithContext(r.context)
}
if r.response != nil {
if mode, ok := r.response["mode"]; ok && mode == "binary" {
request.Header.Set("X-Pixaven-Binary", "1")
}
}
request.SetBasicAuth(r.client.Key, "")
// Run the request using the passed Client
return r.http.Do(request)
}
// ToJSON runs the request and returns a fastjson.Value with a result from the API.
func (r *Request) ToJSON() (*fastjson.Value, error) {
// Run the request
resp, err := r.execute()
if err != nil {
return nil, err
}
// Decode the JSON body into a *fastjson.Value
var parser fastjson.Parser
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
result, err := parser.ParseBytes(body)
if err != nil {
return nil, err
}
// Ensuring that the code won't panic, safely generate an API error struct.
if result != nil {
value := result.Get("success")
if value == nil {
return nil, ErrNoSuccess
}
success, err := value.Bool()
if err != nil {
return nil, ErrNoSuccess
}
if !success {
err := &PixavenError{}
// Populate error's code field
codeValue := result.Get("code")
if codeValue == nil {
return nil, ErrNoSuccess
}
if code, err2 := codeValue.Int(); err2 == nil {
err.Code = code
}
// And the error message
messageValue := result.Get("message")
if messageValue == nil {
return nil, ErrNoSuccess
}
if message, err2 := messageValue.StringBytes(); err2 == nil {
err.Message = string(message)
}
return nil, err
}
}
// The query succeeded!
return result, nil
}
// ToReader executes the request, waits for the result and returns a set of 3 variables:
// - meta map containing the result you would normally get in the body
// - io.ReadCloser containing the resulting file
// - error that should be nil if everything succeeded
// Due to the fact that ToReader performs a binary request, using Webhook
// and Store is forbidden.
func (r *Request) ToReader() (*fastjson.Value, io.ReadCloser, error) {
if r.webhook != nil {
return nil, nil, ErrBinaryWebhook
}
if r.store != nil {
return nil, nil, ErrBinaryStorage
}
// Gets embedded into the request
r.response = P{
"mode": "binary",
}
// Execute the request
resp, err := r.execute()
// Clean up the body if execution fails
var succeeded bool
defer func() {
if !succeeded && resp != nil && resp.Body != nil {
resp.Body.Close()
}
}()
if err != nil {
return nil, nil, err
}
// Try to read the meta object
var meta *fastjson.Value
if sm := resp.Header.Get("X-Pixaven-Meta"); sm != "" {
// Decode the JSON body into a *fastjson.Value
var parser fastjson.Parser
meta, err = parser.Parse(sm)
if err != nil {
return nil, nil, err
}
}
// Check for success and generate an error if something went wrong.
if meta != nil {
successValue := meta.Get("success")
if successValue == nil {
return nil, nil, ErrNoSuccess
}
success, err := successValue.Bool()
if err != nil {
return nil, nil, ErrNoSuccess
}
if !success {
err := &PixavenError{}
// Populate error's code field
codeValue := meta.Get("code")
if codeValue == nil {
return nil, nil, ErrNoSuccess
}
if code, err2 := codeValue.Int(); err2 == nil {
err.Code = code
}
// And the error message
messageValue := meta.Get("message")
if messageValue == nil {
return nil, nil, ErrNoSuccess
}
if message, err2 := messageValue.StringBytes(); err2 == nil {
err.Message = string(message)
}
return nil, nil, err
}
}
// Make sure that the defer function won't close the body
succeeded = true
// Everything succeeded.
return meta, resp.Body, nil
}
// ToFile executes a request, waits for the results and saves them into a file
// created on given path. If a file does not exist, it creates one with the
// passed `perm` file permissions.
// It returns 2 variables:
// - meta map containing the result information
// - error that should be nil if everything succeeded
// Due to the fact that ToFile performs a binary request, using Webhook
// and Store is forbidden.
func (r *Request) ToFile(input string, perm os.FileMode) (*fastjson.Value, error) {
// First part of the functionality is the same as ToReader
meta, reader, err := r.ToReader()
if err != nil {
return nil, err
}
// Create the file, truncate it if it exists.
file, err := os.OpenFile(input, os.O_CREATE|os.O_RDWR|os.O_TRUNC, perm)
if err != nil {
return nil, err
}
defer file.Close()
// Copy the stream contents into the file
if _, err := io.Copy(file, reader); err != nil {
return nil, err
}
// Return the meta array, effectively closing the file.
return meta, nil
}
// CopyTo executes a request, waits for the results and copies it into the
// passed io.Writer.
// It returns 2 variables:
// - meta map containing the result information
// - error that should be nil if everything succeeded
// Due to the fact that CopyTo performs a binary request, using Webhook
// and Store is forbidden.
func (r *Request) CopyTo(input io.Writer) (*fastjson.Value, error) {
// First part of the functionality is the same as ToReader
meta, reader, err := r.ToReader()
if err != nil {
return nil, err
}
// Copy the stream contents into the file
if _, err := io.Copy(input, reader); err != nil {
return nil, err
}
// Return the meta array, effectively closing the file.
return meta, nil
}