-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest_test.go
More file actions
963 lines (744 loc) · 23.7 KB
/
request_test.go
File metadata and controls
963 lines (744 loc) · 23.7 KB
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
package api_test
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/bjaus/api"
)
func TestRequest_path_params(t *testing.T) {
t.Parallel()
type Req struct {
ID string `path:"id"`
}
type Resp struct {
ID string `json:"id"`
}
r := api.New()
api.Get(r, "/items/{id}", func(_ context.Context, req *Req) (*Resp, error) {
return &Resp{ID: req.ID}, nil
})
srv := httptest.NewServer(r)
defer srv.Close()
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL+"/items/abc123", nil)
require.NoError(t, err)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
var body Resp
require.NoError(t, json.NewDecoder(resp.Body).Decode(&body))
assert.Equal(t, "abc123", body.ID)
}
func TestRequest_query_params(t *testing.T) {
t.Parallel()
type Req struct {
Page int `query:"page" default:"1"`
Sort string `query:"sort" default:"name"`
}
type Resp struct {
Page int `json:"page"`
Sort string `json:"sort"`
}
r := api.New()
api.Get(r, "/items", func(_ context.Context, req *Req) (*Resp, error) {
return &Resp{Page: req.Page, Sort: req.Sort}, nil
})
srv := httptest.NewServer(r)
t.Cleanup(srv.Close)
tests := map[string]struct {
query string
expectPage int
expectSort string
}{
"explicit values": {
query: "?page=3&sort=date",
expectPage: 3,
expectSort: "date",
},
"defaults": {
query: "",
expectPage: 1,
expectSort: "name",
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
t.Parallel()
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL+"/items"+tc.query, nil)
require.NoError(t, err)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
var body Resp
require.NoError(t, json.NewDecoder(resp.Body).Decode(&body))
assert.Equal(t, tc.expectPage, body.Page)
assert.Equal(t, tc.expectSort, body.Sort)
})
}
}
func TestRequest_json_body(t *testing.T) {
t.Parallel()
type Req struct {
Name string `json:"name"`
Email string `json:"email"`
}
type Resp struct {
Name string `json:"name"`
Email string `json:"email"`
}
r := api.New()
api.Post(r, "/users", func(_ context.Context, req *Req) (*Resp, error) {
return &Resp{Name: req.Name, Email: req.Email}, nil
})
srv := httptest.NewServer(r)
defer srv.Close()
payload := `{"name":"Alice","email":"alice@example.com"}`
req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, srv.URL+"/users", strings.NewReader(payload))
require.NoError(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
assert.Equal(t, http.StatusOK, resp.StatusCode)
var body Resp
require.NoError(t, json.NewDecoder(resp.Body).Decode(&body))
assert.Equal(t, "Alice", body.Name)
assert.Equal(t, "alice@example.com", body.Email)
}
func TestRequest_mixed_params_and_body(t *testing.T) {
t.Parallel()
type Req struct {
OrgID string `path:"org_id"`
Body struct {
Name string `json:"name"`
}
}
type Resp struct {
OrgID string `json:"org_id"`
Name string `json:"name"`
}
r := api.New()
api.Post(r, "/orgs/{org_id}/users", func(_ context.Context, req *Req) (*Resp, error) {
return &Resp{OrgID: req.OrgID, Name: req.Body.Name}, nil
})
srv := httptest.NewServer(r)
defer srv.Close()
req, err := http.NewRequestWithContext(
context.Background(),
http.MethodPost,
srv.URL+"/orgs/org-42/users",
strings.NewReader(`{"name":"Bob"}`),
)
require.NoError(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
var body Resp
require.NoError(t, json.NewDecoder(resp.Body).Decode(&body))
assert.Equal(t, "org-42", body.OrgID)
assert.Equal(t, "Bob", body.Name)
}
func TestRequest_header_binding(t *testing.T) {
t.Parallel()
type Req struct {
Token string `header:"Authorization"`
}
type Resp struct {
Token string `json:"token"`
}
r := api.New()
api.Get(r, "/auth", func(_ context.Context, req *Req) (*Resp, error) {
return &Resp{Token: req.Token}, nil
})
srv := httptest.NewServer(r)
defer srv.Close()
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL+"/auth", nil)
require.NoError(t, err)
req.Header.Set("Authorization", "Bearer secret")
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
var body Resp
require.NoError(t, json.NewDecoder(resp.Body).Decode(&body))
assert.Equal(t, "Bearer secret", body.Token)
}
func TestRequest_RawRequest_embedding(t *testing.T) {
t.Parallel()
type Req struct {
api.RawRequest
}
type Resp struct {
Method string `json:"method"`
Path string `json:"path"`
}
r := api.New()
api.Get(r, "/raw", func(_ context.Context, req *Req) (*Resp, error) {
return &Resp{
Method: req.Request.Method,
Path: req.Request.URL.Path,
}, nil
})
srv := httptest.NewServer(r)
defer srv.Close()
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL+"/raw", nil)
require.NoError(t, err)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
var body Resp
require.NoError(t, json.NewDecoder(resp.Body).Decode(&body))
assert.Equal(t, "GET", body.Method)
assert.Equal(t, "/raw", body.Path)
}
func TestRequest_void_request(t *testing.T) {
t.Parallel()
type Resp struct {
Message string `json:"message"`
}
r := api.New()
api.Get(r, "/void", func(_ context.Context, _ *api.Void) (*Resp, error) {
return &Resp{Message: "ok"}, nil
})
srv := httptest.NewServer(r)
t.Cleanup(srv.Close)
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL+"/void", nil)
require.NoError(t, err)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
assert.Equal(t, http.StatusOK, resp.StatusCode)
var body struct {
Message string `json:"message"`
}
require.NoError(t, json.NewDecoder(resp.Body).Decode(&body))
assert.Equal(t, "ok", body.Message)
}
func TestRequest_cookie_binding(t *testing.T) {
t.Parallel()
type Req struct {
Session string `cookie:"session_id"`
}
type Resp struct {
Session string `json:"session"`
}
r := api.New()
api.Get(r, "/session", func(_ context.Context, req *Req) (*Resp, error) {
return &Resp{Session: req.Session}, nil
})
srv := httptest.NewServer(r)
t.Cleanup(srv.Close)
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL+"/session", nil)
require.NoError(t, err)
req.AddCookie(&http.Cookie{Name: "session_id", Value: "abc123"})
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
var body Resp
require.NoError(t, json.NewDecoder(resp.Body).Decode(&body))
assert.Equal(t, "abc123", body.Session)
}
func TestRequest_cookie_default(t *testing.T) {
t.Parallel()
type Req struct {
Session string `cookie:"session_id" default:"default-session"`
}
type Resp struct {
Session string `json:"session"`
}
r := api.New()
api.Get(r, "/session-default", func(_ context.Context, req *Req) (*Resp, error) {
return &Resp{Session: req.Session}, nil
})
srv := httptest.NewServer(r)
t.Cleanup(srv.Close)
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL+"/session-default", nil)
require.NoError(t, err)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
var body Resp
require.NoError(t, json.NewDecoder(resp.Body).Decode(&body))
assert.Equal(t, "default-session", body.Session)
}
func TestRequest_header_default(t *testing.T) {
t.Parallel()
type Req struct {
Accept string `header:"Accept" default:"application/json"`
}
type Resp struct {
Accept string `json:"accept"`
}
r := api.New()
api.Get(r, "/header-default", func(_ context.Context, req *Req) (*Resp, error) {
return &Resp{Accept: req.Accept}, nil
})
srv := httptest.NewServer(r)
t.Cleanup(srv.Close)
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL+"/header-default", nil)
require.NoError(t, err)
// Do not set Accept header, let default apply.
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
var body Resp
require.NoError(t, json.NewDecoder(resp.Body).Decode(&body))
assert.Equal(t, "application/json", body.Accept)
}
func TestRequest_setFieldValue_types(t *testing.T) {
t.Parallel()
type Req struct {
Duration string `query:"dur"`
Price float64 `query:"price"`
Active bool `query:"active"`
Count int `query:"count"`
}
type Resp struct {
Duration string `json:"duration"`
Price float64 `json:"price"`
Active bool `json:"active"`
Count int `json:"count"`
}
r := api.New()
api.Get(r, "/types", func(_ context.Context, req *Req) (*Resp, error) {
return &Resp{
Duration: req.Duration,
Price: req.Price,
Active: req.Active,
Count: req.Count,
}, nil
})
srv := httptest.NewServer(r)
t.Cleanup(srv.Close)
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet,
srv.URL+"/types?dur=5s&price=19.99&active=true&count=42", nil)
require.NoError(t, err)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
assert.Equal(t, http.StatusOK, resp.StatusCode)
var body Resp
require.NoError(t, json.NewDecoder(resp.Body).Decode(&body))
assert.Equal(t, "5s", body.Duration)
assert.InDelta(t, 19.99, body.Price, 0.001)
assert.True(t, body.Active)
assert.Equal(t, 42, body.Count)
}
func TestRequest_setFieldValue_duration(t *testing.T) {
t.Parallel()
type Req struct {
Timeout time.Duration `query:"timeout"`
}
type Resp struct {
TimeoutNs int64 `json:"timeout_ns"`
}
r := api.New()
api.Get(r, "/duration", func(_ context.Context, req *Req) (*Resp, error) {
return &Resp{TimeoutNs: int64(req.Timeout)}, nil
})
srv := httptest.NewServer(r)
t.Cleanup(srv.Close)
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet,
srv.URL+"/duration?timeout=5s", nil)
require.NoError(t, err)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
assert.Equal(t, http.StatusOK, resp.StatusCode)
var body Resp
require.NoError(t, json.NewDecoder(resp.Body).Decode(&body))
assert.Equal(t, int64(5*time.Second), body.TimeoutNs)
}
func TestRequest_setFieldValue_invalid_int(t *testing.T) {
t.Parallel()
type Req struct {
Count int `query:"count"`
}
r := api.New()
api.Get(r, "/bad-int", func(_ context.Context, _ *Req) (*api.Void, error) {
return &api.Void{}, nil
})
srv := httptest.NewServer(r)
t.Cleanup(srv.Close)
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet,
srv.URL+"/bad-int?count=notanumber", nil)
require.NoError(t, err)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
}
func TestRequest_setFieldValue_invalid_float(t *testing.T) {
t.Parallel()
type Req struct {
Price float64 `query:"price"`
}
r := api.New()
api.Get(r, "/bad-float", func(_ context.Context, _ *Req) (*api.Void, error) {
return &api.Void{}, nil
})
srv := httptest.NewServer(r)
t.Cleanup(srv.Close)
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet,
srv.URL+"/bad-float?price=notafloat", nil)
require.NoError(t, err)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
}
func TestRequest_setFieldValue_invalid_bool(t *testing.T) {
t.Parallel()
type Req struct {
Active bool `query:"active"`
}
r := api.New()
api.Get(r, "/bad-bool", func(_ context.Context, _ *Req) (*api.Void, error) {
return &api.Void{}, nil
})
srv := httptest.NewServer(r)
t.Cleanup(srv.Close)
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet,
srv.URL+"/bad-bool?active=notabool", nil)
require.NoError(t, err)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
}
func TestRequest_setFieldValue_invalid_duration(t *testing.T) {
t.Parallel()
type Req struct {
Timeout time.Duration `query:"timeout"`
}
r := api.New()
api.Get(r, "/bad-dur", func(_ context.Context, _ *Req) (*api.Void, error) {
return &api.Void{}, nil
})
srv := httptest.NewServer(r)
t.Cleanup(srv.Close)
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet,
srv.URL+"/bad-dur?timeout=notaduration", nil)
require.NoError(t, err)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
}
func TestRequest_decodeBody_nil_body(t *testing.T) {
t.Parallel()
type Req struct {
Name string `json:"name"`
}
type Resp struct {
Name string `json:"name"`
}
r := api.New()
api.Post(r, "/nil-body", func(_ context.Context, req *Req) (*Resp, error) {
return &Resp{Name: req.Name}, nil
})
srv := httptest.NewServer(r)
t.Cleanup(srv.Close)
req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, srv.URL+"/nil-body", nil)
require.NoError(t, err)
req.Header.Set("Content-Type", "application/json")
req.ContentLength = 0
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
// Should succeed with empty body (no JSON decode error).
assert.Equal(t, http.StatusOK, resp.StatusCode)
}
func TestRequest_decodeBody_empty_body(t *testing.T) {
t.Parallel()
type Req struct {
Name string `json:"name"`
}
type Resp struct {
Name string `json:"name"`
}
r := api.New()
api.Post(r, "/empty-body", func(_ context.Context, req *Req) (*Resp, error) {
return &Resp{Name: req.Name}, nil
})
srv := httptest.NewServer(r)
t.Cleanup(srv.Close)
// Send request with empty body (EOF).
req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, srv.URL+"/empty-body",
strings.NewReader(""))
require.NoError(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
assert.Equal(t, http.StatusOK, resp.StatusCode)
}
func TestRequest_decodeBody_invalid_json(t *testing.T) {
t.Parallel()
type Req struct {
Name string `json:"name"`
}
r := api.New()
api.Post(r, "/bad-json", func(_ context.Context, _ *Req) (*api.Void, error) {
return &api.Void{}, nil
})
srv := httptest.NewServer(r)
t.Cleanup(srv.Close)
req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, srv.URL+"/bad-json",
strings.NewReader("{invalid json"))
require.NoError(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
}
func TestRequest_setFieldValue_unsupported_type(t *testing.T) {
t.Parallel()
type Req struct {
Data uint `query:"data"`
}
r := api.New()
api.Get(r, "/unsupported", func(_ context.Context, _ *Req) (*api.Void, error) {
return &api.Void{}, nil
})
srv := httptest.NewServer(r)
t.Cleanup(srv.Close)
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet,
srv.URL+"/unsupported?data=42", nil)
require.NoError(t, err)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
// uint is not supported by setFieldValue, should get 400.
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
}
func TestRequest_params_only_no_body(t *testing.T) {
t.Parallel()
type Req struct {
ID string `path:"id"`
Lang string `query:"lang" default:"en"`
}
type Resp struct {
ID string `json:"id"`
Lang string `json:"lang"`
}
r := api.New()
api.Get(r, "/items/{id}", func(_ context.Context, req *Req) (*Resp, error) {
return &Resp{ID: req.ID, Lang: req.Lang}, nil
})
srv := httptest.NewServer(r)
t.Cleanup(srv.Close)
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL+"/items/xyz", nil)
require.NoError(t, err)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
assert.Equal(t, http.StatusOK, resp.StatusCode)
var body Resp
require.NoError(t, json.NewDecoder(resp.Body).Decode(&body))
assert.Equal(t, "xyz", body.ID)
assert.Equal(t, "en", body.Lang)
}
func TestRequest_body_only_nil_body(t *testing.T) {
t.Parallel()
type Req struct {
Name string `json:"name"`
}
type Resp struct {
Name string `json:"name"`
}
r := api.New()
api.Post(r, "/nilbody", func(_ context.Context, req *Req) (*Resp, error) {
return &Resp{Name: req.Name}, nil
})
srv := httptest.NewServer(r)
t.Cleanup(srv.Close)
// Create a POST request with nil body to trigger r.Body == nil path.
req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, srv.URL+"/nilbody", nil)
require.NoError(t, err)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
assert.Equal(t, http.StatusOK, resp.StatusCode)
}
func TestRequest_mixed_body_nil(t *testing.T) {
t.Parallel()
type Req struct {
ID string `path:"id"`
Body struct {
Name string `json:"name"`
}
}
type Resp struct {
ID string `json:"id"`
Name string `json:"name"`
}
r := api.New()
api.Post(r, "/mixed-nil/{id}", func(_ context.Context, req *Req) (*Resp, error) {
return &Resp{ID: req.ID, Name: req.Body.Name}, nil
})
srv := httptest.NewServer(r)
t.Cleanup(srv.Close)
// POST with path param but no body.
req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, srv.URL+"/mixed-nil/abc", nil)
require.NoError(t, err)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
assert.Equal(t, http.StatusOK, resp.StatusCode)
var body Resp
require.NoError(t, json.NewDecoder(resp.Body).Decode(&body))
assert.Equal(t, "abc", body.ID)
}
func TestRequest_path_binding_error(t *testing.T) {
t.Parallel()
type Req struct {
ID int `path:"id"`
}
r := api.New()
api.Get(r, "/items/{id}", func(_ context.Context, req *Req) (*api.Void, error) {
return &api.Void{}, nil
})
srv := httptest.NewServer(r)
t.Cleanup(srv.Close)
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL+"/items/notanint", nil)
require.NoError(t, err)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
}
func TestRequest_header_binding_error(t *testing.T) {
t.Parallel()
type Req struct {
Count int `header:"X-Count"`
}
r := api.New()
api.Get(r, "/header-err", func(_ context.Context, req *Req) (*api.Void, error) {
return &api.Void{}, nil
})
srv := httptest.NewServer(r)
t.Cleanup(srv.Close)
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL+"/header-err", nil)
require.NoError(t, err)
req.Header.Set("X-Count", "notanint")
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
}
func TestRequest_cookie_binding_error(t *testing.T) {
t.Parallel()
type Req struct {
Count int `cookie:"count"`
}
r := api.New()
api.Get(r, "/cookie-err", func(_ context.Context, req *Req) (*api.Void, error) {
return &api.Void{}, nil
})
srv := httptest.NewServer(r)
t.Cleanup(srv.Close)
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL+"/cookie-err", nil)
require.NoError(t, err)
req.AddCookie(&http.Cookie{Name: "count", Value: "notanint"})
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
}
func TestRequest_body_only_with_nil_http_body(t *testing.T) {
t.Parallel()
type Req struct {
Name string `json:"name"`
}
type Resp struct {
Name string `json:"name"`
}
r := api.New()
api.Post(r, "/nilhttpbody", func(_ context.Context, req *Req) (*Resp, error) {
return &Resp{Name: req.Name}, nil
})
// Directly call ServeHTTP with a request that has nil Body but non-zero ContentLength.
rec := httptest.NewRecorder()
req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/nilhttpbody", nil)
require.NoError(t, err)
req.Body = nil // explicitly nil
req.ContentLength = 100 // pretend there's content to avoid ContentLength==0 shortcut
r.ServeHTTP(rec, req)
assert.Equal(t, http.StatusOK, rec.Code)
}
type reqWithUnexported struct {
ID string `path:"id"`
internal string //nolint:unused
}
func TestRequest_bindParams_skips_unexported(t *testing.T) {
t.Parallel()
type Resp struct {
ID string `json:"id"`
}
r := api.New()
api.Get(r, "/unexported/{id}", func(_ context.Context, req *reqWithUnexported) (*Resp, error) {
return &Resp{ID: req.ID}, nil
})
srv := httptest.NewServer(r)
t.Cleanup(srv.Close)
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL+"/unexported/abc", nil)
require.NoError(t, err)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
assert.Equal(t, http.StatusOK, resp.StatusCode)
var body Resp
require.NoError(t, json.NewDecoder(resp.Body).Decode(&body))
assert.Equal(t, "abc", body.ID)
}
func TestRequest_decodeBody_eof_body(t *testing.T) {
t.Parallel()
type Req struct {
Name string `json:"name"`
}
type Resp struct {
Name string `json:"name"`
}
r := api.New()
api.Post(r, "/eof-body", func(_ context.Context, req *Req) (*Resp, error) {
return &Resp{Name: req.Name}, nil
})
// Create a request with an empty body but non-zero ContentLength to hit the EOF path.
rec := httptest.NewRecorder()
req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/eof-body",
strings.NewReader(""))
require.NoError(t, err)
req.ContentLength = -1 // unknown length, forces json.Decode to read, which gets EOF
r.ServeHTTP(rec, req)
assert.Equal(t, http.StatusOK, rec.Code)
}
func TestRequest_mixed_body_invalid_json(t *testing.T) {
t.Parallel()
type Req struct {
ID string `path:"id"`
Body struct {
Name string `json:"name"`
}
}
r := api.New()
api.Post(r, "/mixed-badjson/{id}", func(_ context.Context, req *Req) (*api.Void, error) {
return &api.Void{}, nil
})
srv := httptest.NewServer(r)
t.Cleanup(srv.Close)
req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, srv.URL+"/mixed-badjson/abc",
strings.NewReader("{invalid"))
require.NoError(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
}