-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinder_test.go
More file actions
822 lines (674 loc) · 19.3 KB
/
binder_test.go
File metadata and controls
822 lines (674 loc) · 19.3 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
package binder
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
// CustomTime implements TextUnmarshaler for testing
type CustomTime struct {
Time time.Time
}
func (ct *CustomTime) UnmarshalText(text []byte) error {
t, err := time.Parse("2006-01-02", string(text))
if err != nil {
return err
}
ct.Time = t
return nil
}
// ValidationStruct implements Validator for testing
type ValidationStruct struct {
Value int `path:"value"`
}
func (v ValidationStruct) Validate() error {
if v.Value < 0 {
return fmt.Errorf("value must be positive")
}
return nil
}
func TestBindInt(t *testing.T) {
r := httptest.NewRequest("GET", "/test", nil)
r.SetPathValue("id", "123")
type params struct {
ID int `path:"id"`
}
var p params
err := Bind(r, &p)
if err != nil {
t.Errorf("Binding failed with error: %v", err)
}
if p.ID != 123 {
t.Errorf("Expected ID to be 123, got %d", p.ID)
}
}
func TestBindUUID(t *testing.T) {
r := httptest.NewRequest("GET", "/test", nil)
r.SetPathValue("id", "f47ac10b-58cc-0372-8562-0b8e853961a1")
type params struct {
ID uuid.UUID `path:"id"`
}
var p params
err := Bind(r, &p)
if err != nil {
t.Errorf("Binding failed with error: %v", err)
}
expectedUUID := "f47ac10b-58cc-0372-8562-0b8e853961a1"
if p.ID.String() != expectedUUID {
t.Errorf("Expected ID to be %s, got %s", expectedUUID, p.ID.String())
}
}
func TestBindQuery(t *testing.T) {
r := httptest.NewRequest("GET", "/test?name=Hecate&count=42&price=19.99&flag=true", nil)
type params struct {
Name string `query:"name"`
Count int `query:"count"`
Price float64 `query:"price"`
Flag bool `query:"flag"`
}
var p params
err := Bind(r, &p)
if err != nil {
t.Errorf("Binding failed with error: %v", err)
}
if p.Name != "Hecate" {
t.Errorf("Expected Name to be Hecate, got %s", p.Name)
}
if p.Count != 42 {
t.Errorf("Expected Count to be 42, got %d", p.Count)
}
if p.Price != 19.99 {
t.Errorf("Expected Price to be 19.99, got %f", p.Price)
}
if !p.Flag {
t.Errorf("Expected Flag to be true, got %v", p.Flag)
}
}
func TestBindCookie(t *testing.T) {
r := httptest.NewRequest("GET", "/test", nil)
r.AddCookie(&http.Cookie{Name: "token", Value: "abc123"})
r.AddCookie(&http.Cookie{Name: "user_id", Value: "456"})
type params struct {
Token string `cookie:"token"`
UserID int `cookie:"user_id"`
}
var p params
err := Bind(r, &p)
if err != nil {
t.Errorf("Binding failed with error: %v", err)
}
if p.Token != "abc123" {
t.Errorf("Expected Token to be abc123, got %s", p.Token)
}
if p.UserID != 456 {
t.Errorf("Expected UserID to be 456, got %d", p.UserID)
}
}
func TestBindTextUnmarshaler(t *testing.T) {
r := httptest.NewRequest("GET", "/test", nil)
r.SetPathValue("date", "2023-05-15")
type params struct {
Date CustomTime `path:"date"`
}
var p params
err := Bind(r, &p)
if err != nil {
t.Errorf("Binding failed with error: %v", err)
}
if p.Date.Time.Year() != 2023 {
t.Errorf("Expected year to be 2023, got %d", p.Date.Time.Year())
}
if p.Date.Time.Month() != time.Month(5) {
t.Errorf("Expected month to be 5, got %d", p.Date.Time.Month())
}
if p.Date.Time.Day() != 15 {
t.Errorf("Expected day to be 15, got %d", p.Date.Time.Day())
}
}
func TestBindValidationSuccess(t *testing.T) {
r := httptest.NewRequest("GET", "/test", nil)
r.SetPathValue("value", "10")
var p ValidationStruct
err := Bind(r, &p)
if err != nil {
t.Errorf("Binding should succeed with positive value, got error: %v", err)
}
if p.Value != 10 {
t.Errorf("Expected Value to be 10, got %d", p.Value)
}
}
func TestBindValidationFailure(t *testing.T) {
r := httptest.NewRequest("GET", "/test", nil)
r.SetPathValue("value", "-10")
var p ValidationStruct
err := Bind(r, &p)
if err == nil {
t.Errorf("Binding should fail with negative value")
}
if !strings.Contains(err.Error(), "validation failed") {
t.Errorf("Expected validation error, got: %v", err)
}
}
func TestBindOmitEmpty(t *testing.T) {
r := httptest.NewRequest("GET", "/test?name=TestName", nil)
type params struct {
ID int `query:"id,omitempty"`
Name string `query:"name,omitempty"`
}
var p params
p.ID = 999 // Default value
p.Name = "DefaultName"
err := Bind(r, &p)
if err != nil {
t.Errorf("Binding failed with error: %v", err)
}
if p.ID != 999 {
t.Errorf("Expected ID to remain 999, got %d", p.ID)
}
if p.Name != "TestName" {
t.Errorf("Expected Name to be TestName, got %s", p.Name)
}
}
func TestBindJsonBody(t *testing.T) {
type nested struct {
NEmail string `body:"email"`
Count int `body:"count"`
}
type params struct {
UID uuid.UUID `body:"uid"`
Email string `body:"email"`
Active bool `body:"active"`
Amount float64 `body:"amount"`
Nested nested `body:"nested"`
Nums []int `body:"nums"`
Tags []string `body:"tags"`
}
payload := map[string]interface{}{
"email": "info@example.io",
"uid": "f47ac10b-58cc-0372-8562-0b8e853961a1",
"active": true,
"amount": 99.99,
"nested": map[string]interface{}{
"email": "nested@example.io",
"count": 42,
},
"nums": []int{13, 24, 35},
"tags": []string{"tag1", "tag2", "tag3"},
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
t.Fatalf("Failed to marshal JSON: %v", err)
}
r := httptest.NewRequest("POST", "/test", bytes.NewBuffer(payloadBytes))
r.Header.Set("Content-Type", "application/json")
var p params
err = Bind(r, &p)
if err != nil {
t.Errorf("Binding failed with error: %v", err)
}
if p.UID.String() != "f47ac10b-58cc-0372-8562-0b8e853961a1" {
t.Errorf("Expected UID to be f47ac10b-58cc-0372-8562-0b8e853961a1, got %s", p.UID)
}
if p.Email != "info@example.io" {
t.Errorf("Expected Email to be info@example.io, got %s", p.Email)
}
if !p.Active {
t.Errorf("Expected Active to be true, got %v", p.Active)
}
if p.Amount != 99.99 {
t.Errorf("Expected Amount to be 99.99, got %f", p.Amount)
}
if p.Nested.NEmail != "nested@example.io" {
t.Errorf("Expected Nested.NEmail to be nested@example.io, got %s", p.Nested.NEmail)
}
if p.Nested.Count != 42 {
t.Errorf("Expected Nested.Count to be 42, got %d", p.Nested.Count)
}
expectedNums := []int{13, 24, 35}
if !reflect.DeepEqual(p.Nums, expectedNums) {
t.Errorf("Expected Nums to be %v, got %v", expectedNums, p.Nums)
}
expectedTags := []string{"tag1", "tag2", "tag3"}
if !reflect.DeepEqual(p.Tags, expectedTags) {
t.Errorf("Expected Tags to be %v, got %v", expectedTags, p.Tags)
}
}
func TestBindFormBody(t *testing.T) {
formData := url.Values{}
formData.Add("email", "test@example.io")
formData.Add("flag", "false")
formData.Add("count", "42")
formData.Add("amount", "99.99")
r := httptest.NewRequest("POST", "/test", strings.NewReader(formData.Encode()))
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
type params struct {
Email string `body:"email"`
Flag bool `body:"flag"`
Count int `body:"count"`
Amount float64 `body:"amount"`
}
var p params
err := Bind(r, &p)
if err != nil {
t.Errorf("Binding failed with error: %v", err)
}
if p.Email != "test@example.io" {
t.Errorf("Expected Email to be test@example.io, got %s", p.Email)
}
if p.Flag {
t.Errorf("Expected Flag to be false, got %v", p.Flag)
}
if p.Count != 42 {
t.Errorf("Expected Count to be 42, got %d", p.Count)
}
if p.Amount != 99.99 {
t.Errorf("Expected Amount to be 99.99, got %f", p.Amount)
}
}
func TestBindMultipleBodyReads(t *testing.T) {
payload := map[string]interface{}{
"name": "Test User",
"email": "test@example.com",
"age": 30,
"active": true,
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
t.Fatalf("Failed to marshal JSON: %v", err)
}
r := httptest.NewRequest("POST", "/test", bytes.NewBuffer(payloadBytes))
r.Header.Set("Content-Type", "application/json")
// First binding
type params1 struct {
Name string `body:"name"`
Email string `body:"email"`
}
var p1 params1
err = Bind(r, &p1)
if err != nil {
t.Errorf("First binding failed with error: %v", err)
}
if p1.Name != "Test User" {
t.Errorf("Expected Name to be Test User, got %s", p1.Name)
}
if p1.Email != "test@example.com" {
t.Errorf("Expected Email to be test@example.com, got %s", p1.Email)
}
// Second binding - should still work since body is restored
type params2 struct {
Age int `body:"age"`
Active bool `body:"active"`
}
var p2 params2
err = Bind(r, &p2)
if err != nil {
t.Errorf("Second binding failed with error: %v", err)
}
if p2.Age != 30 {
t.Errorf("Expected Age to be 30, got %d", p2.Age)
}
if !p2.Active {
t.Errorf("Expected Active to be true, got %v", p2.Active)
}
}
func TestBindInvalidInt(t *testing.T) {
r := httptest.NewRequest("GET", "/test", nil)
r.SetPathValue("id", "not-an-int")
type params struct {
ID int `path:"id"`
}
var p params
err := Bind(r, &p)
if err == nil {
t.Errorf("Binding should fail with invalid int")
}
if !strings.Contains(err.Error(), "error setting field ID") {
t.Errorf("Expected error about field ID, got: %v", err)
}
}
func TestBindInvalidFloat(t *testing.T) {
r := httptest.NewRequest("GET", "/test?value=not-a-float", nil)
type params struct {
Value float64 `query:"value"`
}
var p params
err := Bind(r, &p)
if err == nil {
t.Errorf("Binding should fail with invalid float")
}
if !strings.Contains(err.Error(), "error setting field Value") {
t.Errorf("Expected error about field Value, got: %v", err)
}
}
func TestBindInvalidBool(t *testing.T) {
r := httptest.NewRequest("GET", "/test?flag=not-a-bool", nil)
type params struct {
Flag bool `query:"flag"`
}
var p params
err := Bind(r, &p)
if err == nil {
t.Errorf("Binding should fail with invalid boolean")
}
if !strings.Contains(err.Error(), "error setting field Flag") {
t.Errorf("Expected error about field Flag, got: %v", err)
}
}
func TestBindInvalidUUID(t *testing.T) {
r := httptest.NewRequest("GET", "/test", nil)
r.SetPathValue("id", "not-a-uuid")
type params struct {
ID uuid.UUID `path:"id"`
}
var p params
err := Bind(r, &p)
if err == nil {
t.Errorf("Binding should fail with invalid UUID")
}
if !strings.Contains(err.Error(), "error setting field ID") {
t.Errorf("Expected error about field ID, got: %v", err)
}
}
func TestBindUnsupportedType(t *testing.T) {
r := httptest.NewRequest("GET", "/test?value=123", nil)
type params struct {
Value complex128 `query:"value"`
}
var p params
err := Bind(r, &p)
if err == nil {
t.Errorf("Binding should fail with unsupported type")
}
if !strings.Contains(err.Error(), "unsupported type") {
t.Errorf("Expected error about unsupported type, got: %v", err)
}
}
func TestBindSlicesExplicitly(t *testing.T) {
t.Run("IntSlice", func(t *testing.T) {
payload := map[string]interface{}{
"values": []int{1, 2, 3, 4, 5},
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
t.Fatalf("Failed to marshal JSON: %v", err)
}
r := httptest.NewRequest("POST", "/test", bytes.NewBuffer(payloadBytes))
r.Header.Set("Content-Type", "application/json")
type params struct {
Values []int `body:"values"`
}
var p params
err = Bind(r, &p)
if err != nil {
t.Errorf("Binding should succeed with int slice, got error: %v", err)
}
expected := []int{1, 2, 3, 4, 5}
if !reflect.DeepEqual(p.Values, expected) {
t.Errorf("Expected Values to be %v, got %v", expected, p.Values)
}
})
t.Run("StringSlice", func(t *testing.T) {
payload := map[string]interface{}{
"tags": []string{"tag1", "tag2", "tag3", "tag4", "tag5"},
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
t.Fatalf("Failed to marshal JSON: %v", err)
}
r := httptest.NewRequest("POST", "/test", bytes.NewBuffer(payloadBytes))
r.Header.Set("Content-Type", "application/json")
type params struct {
Tags []string `body:"tags"`
}
var p params
err = Bind(r, &p)
if err != nil {
t.Errorf("Binding should succeed with string slice, got error: %v", err)
}
expected := []string{"tag1", "tag2", "tag3", "tag4", "tag5"}
if !reflect.DeepEqual(p.Tags, expected) {
t.Errorf("Expected Tags to be %v, got %v", expected, p.Tags)
}
})
t.Run("EmptySlice", func(t *testing.T) {
payload := map[string]interface{}{
"items": []interface{}{},
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
t.Fatalf("Failed to marshal JSON: %v", err)
}
r := httptest.NewRequest("POST", "/test", bytes.NewBuffer(payloadBytes))
r.Header.Set("Content-Type", "application/json")
type params struct {
Items []string `body:"items"`
}
var p params
err = Bind(r, &p)
if err != nil {
t.Errorf("Binding should succeed with empty slice, got error: %v", err)
}
if len(p.Items) != 0 {
t.Errorf("Expected Items to be empty, got %v", p.Items)
}
})
t.Run("BoolSlice", func(t *testing.T) {
payload := map[string]interface{}{
"flags": []bool{true, false, true, true, false},
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
t.Fatalf("Failed to marshal JSON: %v", err)
}
r := httptest.NewRequest("POST", "/test", bytes.NewBuffer(payloadBytes))
r.Header.Set("Content-Type", "application/json")
type params struct {
Flags []bool `body:"flags"`
}
var p params
err = Bind(r, &p)
if err != nil {
t.Errorf("Binding should succeed with bool slice, got error: %v", err)
}
expected := []bool{true, false, true, true, false}
if !reflect.DeepEqual(p.Flags, expected) {
t.Errorf("Expected Flags to be %v, got %v", expected, p.Flags)
}
})
t.Run("FloatSlice", func(t *testing.T) {
payload := map[string]interface{}{
"prices": []float64{1.99, 2.99, 3.99, 4.99},
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
t.Fatalf("Failed to marshal JSON: %v", err)
}
r := httptest.NewRequest("POST", "/test", bytes.NewBuffer(payloadBytes))
r.Header.Set("Content-Type", "application/json")
type params struct {
Prices []float64 `body:"prices"`
}
var p params
err = Bind(r, &p)
if err != nil {
t.Errorf("Binding should succeed with float slice, got error: %v", err)
}
expected := []float64{1.99, 2.99, 3.99, 4.99}
if !reflect.DeepEqual(p.Prices, expected) {
t.Errorf("Expected Prices to be %v, got %v", expected, p.Prices)
}
})
t.Run("SingleValueToSlice", func(t *testing.T) {
// Test binding a single query param value to a slice
r := httptest.NewRequest("GET", "/test?tag=important", nil)
type params struct {
Tag []string `query:"tag"`
}
var p params
err := Bind(r, &p)
if err != nil {
t.Errorf("Binding should succeed with single value to slice, got error: %v", err)
}
expected := []string{"important"}
if !reflect.DeepEqual(p.Tag, expected) {
t.Errorf("Expected Tag to be %v, got %v", expected, p.Tag)
}
})
}
func TestBindArrayNotSupported(t *testing.T) {
payload := map[string]interface{}{
"values": []int{1, 2, 3},
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
t.Fatalf("Failed to marshal JSON: %v", err)
}
r := httptest.NewRequest("POST", "/test", bytes.NewBuffer(payloadBytes))
r.Header.Set("Content-Type", "application/json")
type params struct {
Values [3]int `body:"values"`
}
var p params
err = Bind(r, &p)
if err == nil {
t.Errorf("Binding should fail with array type")
}
if !strings.Contains(err.Error(), "arrays are not supported, use slices instead") {
t.Errorf("Expected error about arrays not supported, got: %v", err)
}
}
func TestFieldCache(t *testing.T) {
type cachedStruct struct {
ID int `path:"id"`
Name string `query:"name"`
}
// Clear the cache before the test
fieldCacheMutex.Lock()
delete(fieldCache, reflect.TypeOf(cachedStruct{}))
fieldCacheMutex.Unlock()
// First access - should build cache
info1 := getFieldInfo(reflect.TypeOf(cachedStruct{}))
if len(info1) != 2 {
t.Errorf("Expected 2 field info entries, got %d", len(info1))
}
// Second access - should use cache
info2 := getFieldInfo(reflect.TypeOf(cachedStruct{}))
// Check equality of the two maps
if len(info1) != len(info2) {
t.Errorf("Expected info1 and info2 to have the same length")
}
// Manual deep equality check
for k, v1 := range info1 {
v2, exists := info2[k]
if !exists {
t.Errorf("Key %s exists in info1 but not in info2", k)
}
if v1.Index != v2.Index || v1.Source != v2.Source || v1.TagName != v2.TagName || v1.OmitEmpty != v2.OmitEmpty {
t.Errorf("Values for key %s differ between info1 and info2", k)
}
}
// Check the cache directly
fieldCacheMutex.RLock()
cachedInfo, exists := fieldCache[reflect.TypeOf(cachedStruct{})]
fieldCacheMutex.RUnlock()
if !exists {
t.Errorf("Type should exist in cache")
}
// Check if cached info equals the returned info
if len(info1) != len(cachedInfo) {
t.Errorf("Expected cachedInfo to have the same length as info1")
}
for k, v1 := range info1 {
v2, exists := cachedInfo[k]
if !exists {
t.Errorf("Key %s exists in info1 but not in cachedInfo", k)
}
if v1.Index != v2.Index || v1.Source != v2.Source || v1.TagName != v2.TagName || v1.OmitEmpty != v2.OmitEmpty {
t.Errorf("Values for key %s differ between info1 and cachedInfo", k)
}
}
}
func TestContentTypeParser(t *testing.T) {
tests := []struct {
header string
expected string
}{
{"application/json", "application/json"},
{"application/json; charset=utf-8", "application/json"},
{"application/json;charset=utf-8", "application/json"},
{"text/plain", "text/plain"},
{"text/plain; charset=iso-8859-1", "text/plain"},
{"", ""},
{" application/json ; charset=utf-8", "application/json"},
}
for _, tt := range tests {
result := parseContentType(tt.header)
if result != tt.expected {
t.Errorf("parseContentType(%q) = %q, want %q", tt.header, result, tt.expected)
}
}
}
func BenchmarkBind(b *testing.B) {
// Test type for binding
type params struct {
ID int `path:"id"`
Name string `query:"name"`
Email string `body:"email"`
Active bool `body:"active"`
UUID uuid.UUID `body:"uuid"`
}
// Create a sample HTTP request
payload := map[string]interface{}{
"email": "test@example.com",
"active": true,
"uuid": "f47ac10b-58cc-0372-8562-0b8e853961a1",
}
payloadBytes, _ := json.Marshal(payload)
req := httptest.NewRequest("POST", "/test?name=TestUser", bytes.NewBuffer(payloadBytes))
req.Header.Set("Content-Type", "application/json")
// Simulate path parameters
req.SetPathValue("id", "123")
b.ResetTimer()
for i := 0; i < b.N; i++ {
var p params
_ = Bind(req, &p)
}
}
func BenchmarkBindWithoutCache(b *testing.B) {
// For comparison - clear cache on each iteration
// Test type for binding
type params struct {
ID int `path:"id"`
Name string `query:"name"`
Email string `body:"email"`
Active bool `body:"active"`
UUID uuid.UUID `body:"uuid"`
}
// Create a sample HTTP request
payload := map[string]interface{}{
"email": "test@example.com",
"active": true,
"uuid": "f47ac10b-58cc-0372-8562-0b8e853961a1",
}
payloadBytes, _ := json.Marshal(payload)
req := httptest.NewRequest("POST", "/test?name=TestUser", bytes.NewBuffer(payloadBytes))
req.Header.Set("Content-Type", "application/json")
// Simulate path parameters
req.SetPathValue("id", "123")
b.ResetTimer()
for i := 0; i < b.N; i++ {
// Clear cache for each iteration
fieldCacheMutex.Lock()
fieldCache = make(map[reflect.Type]map[string]fieldInfo)
fieldCacheMutex.Unlock()
var p params
_ = Bind(req, &p)
}
}