-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconvert.go
More file actions
814 lines (695 loc) · 22.7 KB
/
convert.go
File metadata and controls
814 lines (695 loc) · 22.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
// Copyright 2025 The Rivaas Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package binding
import (
"encoding"
"encoding/json"
"fmt"
"net"
"net/url"
"reflect"
"regexp"
"strconv"
"strings"
"time"
)
// setField sets a single struct field value with type conversion.
// It handles pointer fields by creating a new pointer if the value is non-empty.
func setField(field reflect.Value, value string, isPtr bool, opts *config) error {
fieldType := field.Type()
// Handle pointer fields
if isPtr {
if value == "" {
// Leave nil for empty values
return nil
}
// Create new pointer and set its value
ptr := reflect.New(fieldType.Elem())
if err := setFieldValue(ptr.Elem(), value, opts); err != nil {
return err
}
field.Set(ptr)
return nil
}
return setFieldValue(field, value, opts)
}
// setFieldValue sets the actual field value with type conversion.
// It checks custom converters first, then handles special types, TextUnmarshaler
// interface, and finally primitive types.
func setFieldValue(field reflect.Value, value string, opts *config) error {
fieldType := field.Type()
// Priority 0: Custom type converters (highest priority)
if converter := findConverter(fieldType, opts); converter != nil {
converted, err := converter(value)
if err != nil {
return err
}
// Handle pointer vs value transparently
if fieldType.Kind() == reflect.Pointer {
ptr := reflect.New(fieldType.Elem())
ptr.Elem().Set(reflect.ValueOf(converted))
field.Set(ptr)
} else {
field.Set(reflect.ValueOf(converted))
}
return nil
}
// Priority 1: Handle special types BEFORE checking TextUnmarshaler
// This allows us to provide better parsing for time.Time (which implements TextUnmarshaler)
switch fieldType {
case timeType:
t, err := parseTime(value, opts)
if err != nil {
return err
}
field.Set(reflect.ValueOf(t))
return nil
case durationType:
d, err := time.ParseDuration(value)
if err != nil {
return fmt.Errorf("invalid duration: %w", err)
}
field.Set(reflect.ValueOf(d))
return nil
case urlType:
u, err := url.Parse(value)
if err != nil {
return fmt.Errorf("invalid URL: %w", err)
}
field.Set(reflect.ValueOf(*u))
return nil
case ipType:
ip := net.ParseIP(value)
if ip == nil {
return fmt.Errorf("%w: %s", ErrInvalidIPAddress, value)
}
field.Set(reflect.ValueOf(ip))
return nil
case ipNetType:
_, ipnet, err := net.ParseCIDR(value)
if err != nil {
return fmt.Errorf("invalid CIDR notation: %w", err)
}
field.Set(reflect.ValueOf(*ipnet))
return nil
case regexpType:
re, err := regexp.Compile(value)
if err != nil {
return fmt.Errorf("invalid regular expression: %w", err)
}
field.Set(reflect.ValueOf(*re))
return nil
}
// Priority 2: Check for encoding.TextUnmarshaler interface
// This allows custom types to define their own parsing logic
if field.CanAddr() && field.Addr().Type().Implements(textUnmarshalerType) {
unmarshaler, ok := field.Addr().Interface().(encoding.TextUnmarshaler)
if !ok {
return fmt.Errorf("%w: failed to assert TextUnmarshaler", ErrUnsupportedType)
}
return unmarshaler.UnmarshalText([]byte(value))
}
// Priority 3: Handle primitive types
converted, err := convertValue(value, fieldType.Kind(), opts)
if err != nil {
return err
}
// Set the field value
switch fieldType.Kind() {
case reflect.String:
str, ok := converted.(string)
if !ok {
return fmt.Errorf("%w: expected string, got %T", ErrUnsupportedType, converted)
}
field.SetString(str)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
i, ok := converted.(int64)
if !ok {
return fmt.Errorf("%w: expected int64, got %T", ErrUnsupportedType, converted)
}
field.SetInt(i)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
u, ok := converted.(uint64)
if !ok {
return fmt.Errorf("%w: expected uint64, got %T", ErrUnsupportedType, converted)
}
field.SetUint(u)
case reflect.Float32, reflect.Float64:
f, ok := converted.(float64)
if !ok {
return fmt.Errorf("%w: expected float64, got %T", ErrUnsupportedType, converted)
}
field.SetFloat(f)
case reflect.Bool:
b, ok := converted.(bool)
if !ok {
return fmt.Errorf("%w: expected bool, got %T", ErrUnsupportedType, converted)
}
field.SetBool(b)
default:
return fmt.Errorf("%w: %v", ErrUnsupportedType, fieldType.Kind())
}
return nil
}
// setSliceField sets a slice field from multiple string values.
// It handles CSV mode (comma-separated values) and enforces maximum slice length limits.
func setSliceField(field reflect.Value, values []string, opts *config) error {
if len(values) == 0 {
return nil
}
// Handle CSV mode: if single value and CSV mode enabled, split it
if opts.sliceMode == SliceCSV && len(values) == 1 {
split := strings.Split(values[0], ",")
// Trim whitespace from each element
for i := range split {
split[i] = strings.TrimSpace(split[i])
}
values = split
}
// Enforce maximum slice length
if opts.maxSliceLen > 0 && len(values) > opts.maxSliceLen {
return fmt.Errorf("%w: %d > %d (use WithMaxSliceLen to increase)",
ErrSliceExceedsMaxLength, len(values), opts.maxSliceLen)
}
// Create slice with appropriate capacity
slice := reflect.MakeSlice(field.Type(), len(values), len(values))
// Convert and set each element
for i, val := range values {
elem := slice.Index(i)
// Use setFieldValue for each element to handle special types
if err := setFieldValue(elem, val, opts); err != nil {
return fmt.Errorf("element %d: %w", i, err)
}
}
field.Set(slice)
return nil
}
// convertValue converts a string value to the target reflect.Kind.
// It handles strings, integers, unsigned integers, floats, and booleans.
func convertValue(value string, kind reflect.Kind, opts *config) (any, error) {
switch kind {
case reflect.String:
return value, nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
base := 10
if opts.intBaseAuto {
base = 0 // Auto-detect: 0x=hex, 0=octal, 0b=binary
}
i, err := strconv.ParseInt(value, base, 64)
if err != nil {
return nil, fmt.Errorf("invalid integer: %w", err)
}
return i, nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
base := 10
if opts.intBaseAuto {
base = 0 // Auto-detect: 0x=hex, 0=octal, 0b=binary
}
u, err := strconv.ParseUint(value, base, 64)
if err != nil {
return nil, fmt.Errorf("invalid unsigned integer: %w", err)
}
return u, nil
case reflect.Float32, reflect.Float64:
f, err := strconv.ParseFloat(value, 64)
if err != nil {
return nil, fmt.Errorf("invalid float: %w", err)
}
return f, nil
case reflect.Bool:
b, err := parseBoolGenerous(value)
if err != nil {
return nil, err
}
return b, nil
default:
return nil, fmt.Errorf("%w: %v", ErrUnsupportedType, kind)
}
}
// parseBoolGenerous parses various boolean string representations.
// It supports: true/false, 1/0, yes/no, on/off, t/f, y/n (case-insensitive).
func parseBoolGenerous(s string) (bool, error) {
lower := strings.ToLower(strings.TrimSpace(s))
switch lower {
case "true", "1", "yes", "on", "t", "y":
return true, nil
case "false", "0", "no", "off", "f", "n", "":
return false, nil
default:
return false, fmt.Errorf("%w: %q", ErrInvalidBooleanValue, s)
}
}
// parseTime attempts to parse a time string using multiple formats.
// It tries default formats first (RFC3339, date-only, etc.), then custom layouts
// from options. Returns an error if no format matches.
func parseTime(value string, opts *config) (time.Time, error) {
value = strings.TrimSpace(value)
if value == "" {
return time.Time{}, ErrEmptyTimeValue
}
// Try default formats first (most common)
defaultFormats := []string{
time.RFC3339, // 2024-01-15T10:30:00Z (ISO 8601)
time.RFC3339Nano, // with nanoseconds
time.DateOnly, // Date only: 2024-01-15
time.DateTime, // DateTime: 2024-01-15 10:30:00
time.RFC1123, // Mon, 02 Jan 2006 15:04:05 MST
time.RFC1123Z, // Mon, 02 Jan 2006 15:04:05 -0700
time.RFC822, // 02 Jan 06 15:04 MST
time.RFC822Z, // 02 Jan 06 15:04 -0700
time.RFC850, // Monday, 02-Jan-06 15:04:05 MST
"2006-01-02T15:04:05", // DateTime without timezone
}
// Try default formats
for _, format := range defaultFormats {
if t, err := time.Parse(format, value); err == nil {
return t, nil
}
}
// Try custom layouts from options
for _, layout := range opts.timeLayouts {
if t, err := time.Parse(layout, value); err == nil {
return t, nil
}
}
return time.Time{}, fmt.Errorf("%w %q (tried RFC3339, date-only, and other common formats)", ErrUnableToParseTime, value)
}
// convertSliceDefault converts a comma-separated default string into a typed slice.
// Each element is trimmed and converted via setFieldValue.
func convertSliceDefault(value string, sliceType reflect.Type, cfg *config) (any, error) {
parts := strings.Split(value, ",")
for i := range parts {
parts[i] = strings.TrimSpace(parts[i])
}
slice := reflect.MakeSlice(sliceType, len(parts), len(parts))
for i, part := range parts {
if err := setFieldValue(slice.Index(i), part, cfg); err != nil {
return nil, fmt.Errorf("element %d: %w", i, err)
}
}
return slice.Interface(), nil
}
// splitAndTrimCSV splits a comma-separated string and trims whitespace from each element.
func splitAndTrimCSV(s string) []string {
parts := strings.Split(s, ",")
for i := range parts {
parts[i] = strings.TrimSpace(parts[i])
}
return parts
}
// convertToType converts a string value to the target reflect.Type.
// It handles any types and delegates to setFieldValue for concrete types.
func convertToType(value string, targetType reflect.Type, opts *config) (reflect.Value, error) {
// Handle any
if targetType.Kind() == reflect.Interface {
return reflect.ValueOf(value), nil
}
// For concrete types, use setFieldValue logic
temp := reflect.New(targetType).Elem()
if err := setFieldValue(temp, value, opts); err != nil {
return reflect.Value{}, err
}
return temp, nil
}
// setMapField handles binding data to map fields using dot or bracket notation.
//
// SUPPORTED SYNTAXES:
//
// 1. Dot Notation (clean, recommended):
//
// ?mapName.key1=value1&mapName.key2=value2
//
// 2. Bracket Notation (PHP-style):
//
// ?mapName[key1]=value1&mapName[key2]=value2
//
// 3. Quoted Keys (for special characters):
//
// ?mapName["user.name"]=John&mapName['user-email']=test@example.com
//
// 4. Mixed Syntax (both work together):
//
// ?metadata.key1=val1&metadata[key2]=val2
//
// Supported map types:
// - map[string]string, map[string]int, map[string]float64
// - map[string]bool, map[string]time.Time, map[string]time.Duration
// - map[string]net.IP, map[string]any
func setMapField(field reflect.Value, getter ValueGetter, prefix string, fieldType reflect.Type, opts *config) error {
mapType := fieldType
isPtr := mapType.Kind() == reflect.Pointer
if isPtr {
mapType = mapType.Elem() // Extract element type from pointer
}
// Only support map[string]T
if mapType.Key().Kind() != reflect.String {
return fmt.Errorf("%w, got %v", ErrOnlyMapStringTSupported, mapType)
}
// Estimate capacity and enforce limit
capacity := estimateMapCapacity(getter, prefix)
if opts.maxMapSize > 0 && capacity > opts.maxMapSize {
return fmt.Errorf("%w: %d > %d (use WithMaxMapSize to increase)",
ErrMapExceedsMaxSize, capacity, opts.maxMapSize)
}
// Get the actual map value (dereference if pointer)
mapField := field
if isPtr {
if field.IsNil() {
ptr := reflect.New(mapType)
ptr.Elem().Set(reflect.MakeMap(mapType))
field.Set(ptr)
}
mapField = field.Elem()
} else {
// Create map with estimated capacity
if mapField.IsNil() {
mapField.Set(reflect.MakeMapWithSize(mapType, capacity))
}
}
prefixDot := prefix + "."
prefixBracket := prefix + "["
valueType := mapType.Elem()
found := false
entryCount := 0
// For query/form getters, check all keys for both syntaxes
if qg, ok := getter.(*QueryGetter); ok {
var err error
var foundQuery bool
foundQuery, entryCount, err = bindMapFromValues(
qg.values, qg.Get, prefixDot, prefixBracket, prefix,
mapField, valueType, opts, entryCount,
)
if err != nil {
return err
}
found = found || foundQuery
}
// Also check formGetter for form data (accumulate into existing map)
if fg, ok := getter.(*FormGetter); ok {
var err error
var foundForm bool
foundForm, _, err = bindMapFromValues(
fg.values, fg.Get, prefixDot, prefixBracket, prefix,
mapField, valueType, opts, entryCount,
)
if err != nil {
return err
}
found = found || foundForm // Combine the found flags
}
// If no dot/bracket keys found, try JSON string parsing as fallback
if !found && getter.Has(prefix) {
if err := parseJSONToMap(getter.Get(prefix), mapField, valueType, opts); err != nil {
return err
}
}
return nil
}
// bindMapFromValues iterates over values and binds matching keys to the map field.
// It supports both dot notation (?map.key=value) and bracket notation (?map[key]=value).
// Returns whether any keys were found, the updated entry count, and any error.
func bindMapFromValues(
values map[string][]string,
getValue func(string) string,
prefixDot, prefixBracket, prefix string,
mapField reflect.Value,
valueType reflect.Type,
opts *config,
entryCount int,
) (bool, int, error) {
found := false
for key := range values {
mapKey, ok := extractMapKey(key, prefixDot, prefixBracket, prefix)
if !ok {
continue
}
if mapKey == "" {
return false, entryCount, fmt.Errorf("%w: %s", ErrInvalidBracketNotation, key)
}
found = true
// Enforce limit during iteration
if opts.maxMapSize > 0 {
entryCount++
if entryCount > opts.maxMapSize {
return false, entryCount, fmt.Errorf("%w: %d > %d (use WithMaxMapSize to increase)",
ErrMapExceedsMaxSize, entryCount, opts.maxMapSize)
}
}
value := getValue(key)
convertedValue, err := convertToType(value, valueType, opts)
if err != nil {
return false, entryCount, fmt.Errorf("key %q: %w", mapKey, err)
}
mapField.SetMapIndex(reflect.ValueOf(mapKey), convertedValue)
}
return found, entryCount, nil
}
// extractMapKey extracts the map key from a full key using dot or bracket notation.
// Returns the key and true if matched, empty string and false if no match,
// or empty string and true if bracket notation is invalid (signals an error).
func extractMapKey(fullKey, prefixDot, prefixBracket, prefix string) (string, bool) {
// Pattern 1: Dot notation (?map.key=value)
if key, ok := strings.CutPrefix(fullKey, prefixDot); ok {
return key, true
}
// Pattern 2: Bracket notation (?map[key]=value)
if strings.HasPrefix(fullKey, prefixBracket) {
extractedKey := extractBracketKey(fullKey, prefix)
// Empty key from bracket notation is invalid (return true to signal error)
return extractedKey, true
}
return "", false
}
// parseJSONToMap attempts to parse a JSON string and populate the map field.
func parseJSONToMap(jsonValue string, mapField reflect.Value, valueType reflect.Type, opts *config) error {
if jsonValue == "" {
return nil
}
tempMap := make(map[string]any)
if err := json.Unmarshal([]byte(jsonValue), &tempMap); err != nil {
// Not valid JSON, skip silently (fallback behavior)
return nil
}
for k, v := range tempMap {
strValue := fmt.Sprint(v)
convertedValue, err := convertToType(strValue, valueType, opts)
if err != nil {
return fmt.Errorf("key %q: %w", k, err)
}
mapField.SetMapIndex(reflect.ValueOf(k), convertedValue)
}
return nil
}
// extractBracketKey extracts the map key from bracket notation.
//
// Supported formats:
// - "metadata[name]" → "name"
// - "metadata[\"user.name\"]" → "user.name"
// - "metadata['key-with-dash']" → "key-with-dash"
//
// Invalid formats return an empty string:
// - "metadata[]" → "" (empty brackets, array notation)
// - "metadata[unclosed" → "" (no closing bracket)
// - "metadata[a][b]" → "" (nested brackets, array notation)
func extractBracketKey(fullKey, prefix string) string {
// Remove prefix
if !strings.HasPrefix(fullKey, prefix+"[") {
return ""
}
after := strings.TrimPrefix(fullKey, prefix+"[")
// Find closing bracket
closeBracket := strings.Index(after, "]")
if closeBracket == -1 {
return "" // Malformed - no closing bracket
}
key := after[:closeBracket]
// Check for array notation patterns
// Empty brackets: metadata[]
if key == "" {
return "" // This is array notation, not map
}
// Check for nested brackets after the first closing bracket: metadata[key1][key2]
afterClose := after[closeBracket:]
if strings.Contains(afterClose, "[") {
return "" // This is nested array notation
}
// Handle quoted keys: ["key"] or ['key']
// Remove surrounding quotes (both single and double)
key = strings.Trim(key, `"'`)
// Validate key is not empty after trimming
if key == "" {
return ""
}
return key
}
// setNestedStructWithDepth handles nested struct binding with depth tracking.
// It creates a prefix getter that filters values by the prefix (e.g., "address.")
// and recursively binds the nested struct. Query syntax: ?address.street=Main&address.city=NYC
//
// When field is a pointer-to-struct, it initializes nil pointers and dereferences
// them before binding. This allows binding into fields like *Settings or *Address.
func setNestedStructWithDepth(field reflect.Value, getter ValueGetter, prefix string,
tagName string, opts *config, depth int,
) error {
// Try to parse as JSON first if the field has a direct value (multipart forms with JSON strings)
if jsonValue := getter.Get(prefix); jsonValue != "" && len(jsonValue) > 0 {
// Check if it looks like JSON (starts with { or [)
trimmed := strings.TrimSpace(jsonValue)
if (strings.HasPrefix(trimmed, "{") && strings.HasSuffix(trimmed, "}")) ||
(strings.HasPrefix(trimmed, "[") && strings.HasSuffix(trimmed, "]")) {
// Try to unmarshal as JSON
if field.CanAddr() {
if err := json.Unmarshal([]byte(jsonValue), field.Addr().Interface()); err == nil {
// Successfully parsed as JSON
return nil
}
}
// If JSON parsing fails, fall through to dot-notation parsing
}
}
// Create nested value getter that filters by prefix
nestedGetter := &prefixGetter{
inner: getter,
prefix: prefix + ".",
}
// Handle pointer-to-struct: initialize nil pointers and dereference
structValue := field
structType := field.Type()
if field.Kind() == reflect.Pointer {
// Initialize nil pointer
if field.IsNil() {
field.Set(reflect.New(field.Type().Elem()))
}
// Dereference to get the struct value
structValue = field.Elem()
structType = field.Type().Elem()
}
// Recursively bind nested struct with incremented depth
return bindFieldsWithDepth(structValue, nestedGetter, tagName,
getStructInfo(structType, tagName), opts, depth)
}
// prefixGetter filters values by prefix for nested struct/map binding.
// It prepends the prefix to all key lookups, enabling dot-notation access
// to nested structures.
type prefixGetter struct {
inner ValueGetter
prefix string
}
func (pg *prefixGetter) Get(key string) string {
return pg.inner.Get(pg.prefix + key)
}
func (pg *prefixGetter) GetAll(key string) []string {
return pg.inner.GetAll(pg.prefix + key)
}
func (pg *prefixGetter) Has(key string) bool {
// Check if any key with this prefix exists
fullKey := pg.prefix + key
// Direct check first
if pg.inner.Has(fullKey) {
return true
}
// For nested structs/maps, check if any key starts with prefix
if qg, ok := pg.inner.(*QueryGetter); ok {
for k := range qg.values {
if k == fullKey || strings.HasPrefix(k, fullKey+".") {
return true
}
}
}
if fg, ok := pg.inner.(*FormGetter); ok {
for k := range fg.values {
if k == fullKey || strings.HasPrefix(k, fullKey+".") {
return true
}
}
}
return false
}
// findConverter locates a registered converter for the given type.
// It checks for direct matches, pointer normalization (T vs *T), and interface
// implementations. Returns nil if no converter is found.
func findConverter(fieldType reflect.Type, opts *config) TypeConverter {
if opts.typeConverters == nil {
return nil
}
// Direct match: registered for exact type
if conv, ok := opts.typeConverters[fieldType]; ok {
return conv
}
// Pointer normalization: if field is *T, check for converter registered for T
if fieldType.Kind() == reflect.Pointer {
if conv, ok := opts.typeConverters[fieldType.Elem()]; ok {
return conv // Will be wrapped transparently by caller
}
}
// Interface match: check if any registered interface is implemented by this type
for regType, conv := range opts.typeConverters {
if regType.Kind() == reflect.Interface && fieldType.Implements(regType) {
return conv
}
// Also check pointer receiver
if regType.Kind() == reflect.Interface && reflect.PointerTo(fieldType).Implements(regType) {
return conv
}
}
return nil
}
// estimateMapCapacity estimates the number of map entries for a given prefix.
// It uses the approxSizer interface if available, otherwise returns a default capacity.
func estimateMapCapacity(getter ValueGetter, prefix string) int {
// Check if getter implements approxSizer capability
if sizer, ok := getter.(approxSizer); ok {
if count := sizer.ApproxLen(prefix); count > 0 {
return count
}
}
// Fallback to reasonable default
return 8
}
// isFileType returns true if the type is *File or []*File.
func isFileType(t reflect.Type) bool {
return t == fileType || t == fileSliceType
}
// setFileField handles binding for file upload fields (*File or []*File).
// It checks if the getter implements FileGetter and retrieves the file(s).
func setFileField(field reflect.Value, getter ValueGetter, name string) error {
// Check if getter supports file uploads
fg, ok := getter.(FileGetter)
if !ok {
// Not a multipart source, skip silently
return nil
}
fieldType := field.Type()
// Handle []*File (slice of files)
if fieldType == fileSliceType {
files, err := fg.Files(name)
if err != nil {
// Only return error if field is required (no default), otherwise skip
return err
}
field.Set(reflect.ValueOf(files))
return nil
}
// Handle *File (single file)
if fieldType == fileType {
file, err := fg.File(name)
if err != nil {
// Only return error if field is required, otherwise skip
return err
}
field.Set(reflect.ValueOf(file))
return nil
}
return nil
}