forked from earthboundkid/requests
-
Notifications
You must be signed in to change notification settings - Fork 0
/
builder_example_test.go
585 lines (538 loc) · 12.5 KB
/
builder_example_test.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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
package requests_test
import (
"bytes"
"context"
"encoding/csv"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"github.com/carlmjohnson/requests"
)
func init() {
http.DefaultClient.Transport = requests.Replay("testdata")
}
func Example() {
// Simple GET into a string
var s string
err := requests.
URL("http://example.com").
ToString(&s).
Fetch(context.Background())
if err != nil {
fmt.Println("could not connect to example.com:", err)
}
fmt.Println(strings.Contains(s, "Example Domain"))
// Output:
// true
}
func Example_getJSON() {
// GET a JSON object
id := 1
var post placeholder
err := requests.
URL("https://jsonplaceholder.typicode.com").
Pathf("/posts/%d", id).
ToJSON(&post).
Fetch(context.Background())
if err != nil {
fmt.Println("could not connect to jsonplaceholder.typicode.com:", err)
}
fmt.Println(post.Title)
// Output:
// sunt aut facere repellat provident occaecati excepturi optio reprehenderit
}
func Example_postJSON() {
// POST a JSON object and parse the response
var res placeholder
req := placeholder{
Title: "foo",
Body: "baz",
UserID: 1,
}
err := requests.
URL("/posts").
Host("jsonplaceholder.typicode.com").
BodyJSON(&req).
ToJSON(&res).
Fetch(context.Background())
if err != nil {
fmt.Println("could not connect to jsonplaceholder.typicode.com:", err)
}
fmt.Println(res)
// Output:
// {101 foo baz 1}
}
func ExampleBuilder_ToBytesBuffer() {
// Simple GET into a buffer
var buf bytes.Buffer
err := requests.
URL("http://example.com").
ToBytesBuffer(&buf).
Fetch(context.Background())
if err != nil {
fmt.Println("could not connect to example.com:", err)
}
fmt.Println(strings.Contains(buf.String(), "Example Domain"))
// Output:
// true
}
func ExampleBuilder_ToWriter() {
f, err := os.CreateTemp("", "*.to_writer.html")
if err != nil {
log.Fatal(err)
}
defer os.Remove(f.Name()) // clean up
// suppose there is some io.Writer you want to stream to
err = requests.
URL("http://example.com").
ToWriter(f).
Fetch(context.Background())
if err != nil {
log.Fatal(err)
}
if err = f.Close(); err != nil {
log.Fatal(err)
}
stat, err := os.Stat(f.Name())
if err != nil {
log.Fatal(err)
}
fmt.Printf("file is %d bytes\n", stat.Size())
// Output:
// file is 1256 bytes
}
func ExampleBuilder_ToFile() {
dir, err := os.MkdirTemp("", "to_file_*")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir) // clean up
exampleFilename := filepath.Join(dir, "example.txt")
err = requests.
URL("http://example.com").
ToFile(exampleFilename).
Fetch(context.Background())
if err != nil {
log.Fatal(err)
}
stat, err := os.Stat(exampleFilename)
if err != nil {
log.Fatal(err)
}
fmt.Printf("file is %d bytes\n", stat.Size())
// Output:
// file is 1256 bytes
}
type placeholder struct {
ID int `json:"id,omitempty"`
Title string `json:"title"`
Body string `json:"body"`
UserID int `json:"userId"`
}
func ExampleBuilder_Path() {
// Add an ID to a base URL path
id := 1
u, err := requests.
URL("https://api.example.com/posts/").
// inherits path /posts from base URL
Pathf("%d", id).
URL()
if err != nil {
fmt.Println("Error!", err)
}
fmt.Println(u.String())
// Output:
// https://api.example.com/posts/1
}
func ExampleBuilder_CheckStatus() {
// Expect a specific status code
err := requests.
URL("https://jsonplaceholder.typicode.com").
Pathf("/posts/%d", 9001).
CheckStatus(404).
CheckContentType("application/json").
Fetch(context.Background())
if err != nil {
fmt.Println("should be a 404:", err)
} else {
fmt.Println("OK")
}
// Output:
// OK
}
func ExampleBuilder_CheckContentType() {
// Expect a specific status code
err := requests.
URL("https://jsonplaceholder.typicode.com").
Pathf("/posts/%d", 1).
CheckContentType("application/bison").
Fetch(context.Background())
if err != nil {
if re := new(requests.ResponseError); errors.As(err, &re) {
fmt.Println("content-type was", re.Header.Get("Content-Type"))
}
}
// Output:
// content-type was application/json; charset=utf-8
}
// Examples with the Postman echo server
type postman struct {
Args map[string]string `json:"args"`
Data string `json:"data"`
Headers map[string]string `json:"headers"`
JSON map[string]string `json:"json"`
}
func Example_queryParam() {
subdomain := "dev1"
c := 4
u, err := requests.
URL("https://prod.example.com/get?a=1&b=2").
Hostf("%s.example.com", subdomain).
Param("b", "3").
ParamInt("c", c).
URL()
if err != nil {
fmt.Println("Error!", err)
}
fmt.Println(u.String())
// Output:
// https://dev1.example.com/get?a=1&b=3&c=4
}
func ExampleBuilder_Params() {
// Conditionally add parameters
values := url.Values{"a": {"1"}}
values.Set("b", "3")
if "cond" != "example" {
values.Add("b", "4")
values.Set("c", "5")
}
// Then add them to the URL
u, err := requests.
URL("https://www.example.com/get?a=0&z=6").
Params(values).
URL()
if err != nil {
fmt.Println("Error!", err)
}
fmt.Println(u.String())
// Output:
// https://www.example.com/get?a=1&b=3&b=4&c=5&z=6
}
func ExampleBuilder_Header() {
// Set headers
var headers postman
err := requests.
URL("https://postman-echo.com/get").
UserAgent("bond/james-bond").
BasicAuth("bondj", "007!").
ContentType("secret").
Header("martini", "shaken").
ToJSON(&headers).
Fetch(context.Background())
if err != nil {
fmt.Println("problem with postman:", err)
}
fmt.Println(headers.Headers["user-agent"])
fmt.Println(headers.Headers["authorization"])
fmt.Println(headers.Headers["content-type"])
fmt.Println(headers.Headers["martini"])
// Output:
// bond/james-bond
// Basic Ym9uZGo6MDA3IQ==
// secret
// shaken
}
func ExampleBuilder_Headers() {
// Set headers conditionally
h := make(http.Header)
if "x-forwarded-for" != "true" {
h.Add("x-forwarded-for", "127.0.0.1")
}
if "has-trace-id" != "true" {
h.Add("x-trace-id", "abc123")
}
// Then add them to a request
req, err := requests.
URL("https://example.com").
Headers(h).
Request(context.Background())
if err != nil {
fmt.Println("Error!", err)
}
fmt.Println(req.Header)
// Output:
// map[X-Forwarded-For:[127.0.0.1] X-Trace-Id:[abc123]]
}
func ExampleBuilder_Bearer() {
// We get a 401 response if no bearer token is provided
err := requests.
URL("http://httpbin.org/bearer").
CheckStatus(http.StatusUnauthorized).
Fetch(context.Background())
if err != nil {
fmt.Println("problem with httpbin:", err)
}
// But our response is accepted when we provide a bearer token
var res struct {
Authenticated bool
Token string
}
err = requests.
URL("http://httpbin.org/bearer").
Bearer("whatever").
ToJSON(&res).
Fetch(context.Background())
if err != nil {
fmt.Println("problem with httpbin:", err)
}
fmt.Println(res.Authenticated)
fmt.Println(res.Token)
// Output:
// true
// whatever
}
func ExampleBuilder_BodyBytes() {
// Post a raw body
var data postman
err := requests.
URL("https://postman-echo.com/post").
BodyBytes([]byte(`hello, world`)).
ContentType("text/plain").
ToJSON(&data).
Fetch(context.Background())
if err != nil {
fmt.Println("problem with postman:", err)
}
fmt.Println(data.Data)
// Output:
// hello, world
}
func ExampleBuilder_BodyReader() {
// temp file creation boilerplate
dir, err := os.MkdirTemp("", "body_reader_*")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir) // clean up
exampleFilename := filepath.Join(dir, "example.txt")
exampleContent := `hello, world`
if err := os.WriteFile(exampleFilename, []byte(exampleContent), 0644); err != nil {
log.Fatal(err)
}
// suppose there is some io.Reader you want to stream from
f, err := os.Open(exampleFilename)
if err != nil {
log.Fatal(err)
}
defer f.Close()
// send the raw file to server
var echo postman
err = requests.
URL("https://postman-echo.com/post").
ContentType("text/plain").
BodyReader(f).
ToJSON(&echo).
Fetch(context.Background())
if err != nil {
fmt.Println("problem with postman:", err)
}
fmt.Println(echo.Data)
// Output:
// hello, world
}
func ExampleBuilder_CopyHeaders() {
// Get headers while also getting body
var s string
headers := http.Header{}
err := requests.
URL("http://example.com").
CopyHeaders(headers).
// CopyHeaders disables status validation, so add it back
CheckStatus(http.StatusOK).
ToString(&s).
Fetch(context.Background())
if err != nil {
fmt.Println("problem with example.com:", err)
}
fmt.Println(headers.Get("Etag"))
fmt.Println(strings.Contains(s, "Example Domain"))
// Output:
// "3147526947+gzip"
// true
}
func ExampleBuilder_ToHeaders() {
// Send a HEAD request and look at headers
headers := http.Header{}
err := requests.
URL("http://example.com").
ToHeaders(headers).
Fetch(context.Background())
if err != nil {
fmt.Println("problem with example.com:", err)
}
fmt.Println(headers.Get("Etag"))
// Output:
// "3147526947"
}
func ExampleBuilder_BodyWriter() {
var echo postman
err := requests.
URL("https://postman-echo.com/post").
ContentType("text/plain").
BodyWriter(func(w io.Writer) error {
cw := csv.NewWriter(w)
cw.Write([]string{"col1", "col2"})
cw.Write([]string{"val1", "val2"})
cw.Flush()
return cw.Error()
}).
ToJSON(&echo).
Fetch(context.Background())
if err != nil {
fmt.Println("problem with postman:", err)
}
fmt.Printf("%q\n", echo.Data)
// Output:
// "col1,col2\nval1,val2\n"
}
func ExampleBuilder_BodyForm() {
// Submit form values
var echo postman
err := requests.
URL("https://postman-echo.com/put").
Put().
BodyForm(url.Values{
"hello": []string{"world"},
}).
ToJSON(&echo).
Fetch(context.Background())
if err != nil {
fmt.Println("problem with postman:", err)
}
fmt.Println(echo.JSON)
// Output:
// map[hello:world]
}
func ExampleBuilder_BodyFile() {
// Make a file to read from
dir, err := os.MkdirTemp("", "body_file_*")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir) // clean up
exampleFilename := filepath.Join(dir, "example.txt")
exampleContent := `hello, world`
if err = os.WriteFile(exampleFilename, []byte(exampleContent), 0644); err != nil {
log.Fatal(err)
}
// Post a raw file
var data postman
err = requests.
URL("https://postman-echo.com/post").
BodyFile(exampleFilename).
ContentType("text/plain").
ToJSON(&data).
Fetch(context.Background())
if err != nil {
fmt.Println("problem with postman:", err)
}
fmt.Println(data.Data)
// Output:
// hello, world
}
func ExampleBuilder_CheckPeek() {
// Check that a response has a doctype
const doctype = "<!doctype html>"
var s string
err := requests.
URL("http://example.com").
CheckPeek(len(doctype), func(b []byte) error {
if string(b) != doctype {
return fmt.Errorf("missing doctype: %q", b)
}
return nil
}).
ToString(&s).
Fetch(context.Background())
if err != nil {
fmt.Println("could not connect to example.com:", err)
}
fmt.Println(
// Final result still has the prefix
strings.HasPrefix(s, doctype),
// And the full body
strings.HasSuffix(s, "</html>\n"),
)
// Output:
// true true
}
func ExampleBuilder_Transport() {
const text = "Hello, from transport!"
var myCustomTransport requests.RoundTripFunc = func(req *http.Request) (res *http.Response, err error) {
res = &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(strings.NewReader(text)),
}
return
}
var s string
err := requests.
URL("x://transport.example").
Transport(myCustomTransport).
ToString(&s).
Fetch(context.Background())
if err != nil {
fmt.Println("transport failed:", err)
}
fmt.Println(s == text) // true
// Output:
// true
}
func ExampleBuilder_ErrorJSON() {
{
trans := requests.ReplayString(`HTTP/1.1 200 OK
{"x": 1}`)
var goodJSON struct{ X int }
var errJSON struct{ Error string }
err := requests.
URL("http://example.com/").
Transport(trans).
ToJSON(&goodJSON).
ErrorJSON(&errJSON).
Fetch(context.Background())
if err != nil {
fmt.Println("Error!", err)
} else {
fmt.Println("X", goodJSON.X)
}
}
{
trans := requests.ReplayString(`HTTP/1.1 418 I'm a teapot
{"error": "brewing"}`)
var goodJSON struct{ X int }
var errJSON struct{ Error string }
err := requests.
URL("http://example.com/").
Transport(trans).
ToJSON(&goodJSON).
ErrorJSON(&errJSON).
Fetch(context.Background())
switch {
case errors.Is(err, requests.ErrInvalidHandled):
fmt.Println(errJSON.Error)
case err != nil:
fmt.Println("Error!", err)
case err == nil:
fmt.Println("unexpected success")
}
}
// Output:
// X 1
// brewing
}