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 package mapstructure
160
161 import (
162 "encoding/json"
163 "errors"
164 "fmt"
165 "reflect"
166 "sort"
167 "strconv"
168 "strings"
169 )
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185 type DecodeHookFunc interface{}
186
187
188
189 type DecodeHookFuncType func(reflect.Type, reflect.Type, interface{}) (interface{}, error)
190
191
192
193 type DecodeHookFuncKind func(reflect.Kind, reflect.Kind, interface{}) (interface{}, error)
194
195
196
197 type DecodeHookFuncValue func(from reflect.Value, to reflect.Value) (interface{}, error)
198
199
200
201 type DecoderConfig struct {
202
203
204
205
206
207
208
209
210
211 DecodeHook DecodeHookFunc
212
213
214
215
216 ErrorUnused bool
217
218
219
220
221 ZeroFields bool
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240 WeaklyTypedInput bool
241
242
243
244
245
246
247
248 Squash bool
249
250
251
252 Metadata *Metadata
253
254
255
256 Result interface{}
257
258
259
260 TagName string
261 }
262
263
264
265
266
267
268
269 type Decoder struct {
270 config *DecoderConfig
271 }
272
273
274
275 type Metadata struct {
276
277 Keys []string
278
279
280
281 Unused []string
282 }
283
284
285
286 func Decode(input interface{}, output interface{}) error {
287 config := &DecoderConfig{
288 Metadata: nil,
289 Result: output,
290 }
291
292 decoder, err := NewDecoder(config)
293 if err != nil {
294 return err
295 }
296
297 return decoder.Decode(input)
298 }
299
300
301
302 func WeakDecode(input, output interface{}) error {
303 config := &DecoderConfig{
304 Metadata: nil,
305 Result: output,
306 WeaklyTypedInput: true,
307 }
308
309 decoder, err := NewDecoder(config)
310 if err != nil {
311 return err
312 }
313
314 return decoder.Decode(input)
315 }
316
317
318
319 func DecodeMetadata(input interface{}, output interface{}, metadata *Metadata) error {
320 config := &DecoderConfig{
321 Metadata: metadata,
322 Result: output,
323 }
324
325 decoder, err := NewDecoder(config)
326 if err != nil {
327 return err
328 }
329
330 return decoder.Decode(input)
331 }
332
333
334
335
336 func WeakDecodeMetadata(input interface{}, output interface{}, metadata *Metadata) error {
337 config := &DecoderConfig{
338 Metadata: metadata,
339 Result: output,
340 WeaklyTypedInput: true,
341 }
342
343 decoder, err := NewDecoder(config)
344 if err != nil {
345 return err
346 }
347
348 return decoder.Decode(input)
349 }
350
351
352
353
354 func NewDecoder(config *DecoderConfig) (*Decoder, error) {
355 val := reflect.ValueOf(config.Result)
356 if val.Kind() != reflect.Ptr {
357 return nil, errors.New("result must be a pointer")
358 }
359
360 val = val.Elem()
361 if !val.CanAddr() {
362 return nil, errors.New("result must be addressable (a pointer)")
363 }
364
365 if config.Metadata != nil {
366 if config.Metadata.Keys == nil {
367 config.Metadata.Keys = make([]string, 0)
368 }
369
370 if config.Metadata.Unused == nil {
371 config.Metadata.Unused = make([]string, 0)
372 }
373 }
374
375 if config.TagName == "" {
376 config.TagName = "mapstructure"
377 }
378
379 result := &Decoder{
380 config: config,
381 }
382
383 return result, nil
384 }
385
386
387
388 func (d *Decoder) Decode(input interface{}) error {
389 return d.decode("", input, reflect.ValueOf(d.config.Result).Elem())
390 }
391
392
393 func (d *Decoder) decode(name string, input interface{}, outVal reflect.Value) error {
394 var inputVal reflect.Value
395 if input != nil {
396 inputVal = reflect.ValueOf(input)
397
398
399
400 if inputVal.Kind() == reflect.Ptr && inputVal.IsNil() {
401 input = nil
402 }
403 }
404
405 if input == nil {
406
407
408 if d.config.ZeroFields {
409 outVal.Set(reflect.Zero(outVal.Type()))
410
411 if d.config.Metadata != nil && name != "" {
412 d.config.Metadata.Keys = append(d.config.Metadata.Keys, name)
413 }
414 }
415 return nil
416 }
417
418 if !inputVal.IsValid() {
419
420
421 outVal.Set(reflect.Zero(outVal.Type()))
422 if d.config.Metadata != nil && name != "" {
423 d.config.Metadata.Keys = append(d.config.Metadata.Keys, name)
424 }
425 return nil
426 }
427
428 if d.config.DecodeHook != nil {
429
430 var err error
431 input, err = DecodeHookExec(d.config.DecodeHook, inputVal, outVal)
432 if err != nil {
433 return fmt.Errorf("error decoding '%s': %s", name, err)
434 }
435 }
436
437 var err error
438 outputKind := getKind(outVal)
439 addMetaKey := true
440 switch outputKind {
441 case reflect.Bool:
442 err = d.decodeBool(name, input, outVal)
443 case reflect.Interface:
444 err = d.decodeBasic(name, input, outVal)
445 case reflect.String:
446 err = d.decodeString(name, input, outVal)
447 case reflect.Int:
448 err = d.decodeInt(name, input, outVal)
449 case reflect.Uint:
450 err = d.decodeUint(name, input, outVal)
451 case reflect.Float32:
452 err = d.decodeFloat(name, input, outVal)
453 case reflect.Struct:
454 err = d.decodeStruct(name, input, outVal)
455 case reflect.Map:
456 err = d.decodeMap(name, input, outVal)
457 case reflect.Ptr:
458 addMetaKey, err = d.decodePtr(name, input, outVal)
459 case reflect.Slice:
460 err = d.decodeSlice(name, input, outVal)
461 case reflect.Array:
462 err = d.decodeArray(name, input, outVal)
463 case reflect.Func:
464 err = d.decodeFunc(name, input, outVal)
465 default:
466
467 return fmt.Errorf("%s: unsupported type: %s", name, outputKind)
468 }
469
470
471
472 if addMetaKey && d.config.Metadata != nil && name != "" {
473 d.config.Metadata.Keys = append(d.config.Metadata.Keys, name)
474 }
475
476 return err
477 }
478
479
480
481 func (d *Decoder) decodeBasic(name string, data interface{}, val reflect.Value) error {
482 if val.IsValid() && val.Elem().IsValid() {
483 elem := val.Elem()
484
485
486
487
488 copied := false
489 if !elem.CanAddr() {
490 copied = true
491
492
493 copy := reflect.New(elem.Type())
494
495
496 copy.Elem().Set(elem)
497
498
499 elem = copy
500 }
501
502
503
504 if err := d.decode(name, data, elem); err != nil || !copied {
505 return err
506 }
507
508
509 val.Set(elem.Elem())
510 return nil
511 }
512
513 dataVal := reflect.ValueOf(data)
514
515
516
517
518 if dataVal.Kind() == reflect.Ptr && dataVal.Type().Elem() == val.Type() {
519 dataVal = reflect.Indirect(dataVal)
520 }
521
522 if !dataVal.IsValid() {
523 dataVal = reflect.Zero(val.Type())
524 }
525
526 dataValType := dataVal.Type()
527 if !dataValType.AssignableTo(val.Type()) {
528 return fmt.Errorf(
529 "'%s' expected type '%s', got '%s'",
530 name, val.Type(), dataValType)
531 }
532
533 val.Set(dataVal)
534 return nil
535 }
536
537 func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value) error {
538 dataVal := reflect.Indirect(reflect.ValueOf(data))
539 dataKind := getKind(dataVal)
540
541 converted := true
542 switch {
543 case dataKind == reflect.String:
544 val.SetString(dataVal.String())
545 case dataKind == reflect.Bool && d.config.WeaklyTypedInput:
546 if dataVal.Bool() {
547 val.SetString("1")
548 } else {
549 val.SetString("0")
550 }
551 case dataKind == reflect.Int && d.config.WeaklyTypedInput:
552 val.SetString(strconv.FormatInt(dataVal.Int(), 10))
553 case dataKind == reflect.Uint && d.config.WeaklyTypedInput:
554 val.SetString(strconv.FormatUint(dataVal.Uint(), 10))
555 case dataKind == reflect.Float32 && d.config.WeaklyTypedInput:
556 val.SetString(strconv.FormatFloat(dataVal.Float(), 'f', -1, 64))
557 case dataKind == reflect.Slice && d.config.WeaklyTypedInput,
558 dataKind == reflect.Array && d.config.WeaklyTypedInput:
559 dataType := dataVal.Type()
560 elemKind := dataType.Elem().Kind()
561 switch elemKind {
562 case reflect.Uint8:
563 var uints []uint8
564 if dataKind == reflect.Array {
565 uints = make([]uint8, dataVal.Len(), dataVal.Len())
566 for i := range uints {
567 uints[i] = dataVal.Index(i).Interface().(uint8)
568 }
569 } else {
570 uints = dataVal.Interface().([]uint8)
571 }
572 val.SetString(string(uints))
573 default:
574 converted = false
575 }
576 default:
577 converted = false
578 }
579
580 if !converted {
581 return fmt.Errorf(
582 "'%s' expected type '%s', got unconvertible type '%s', value: '%v'",
583 name, val.Type(), dataVal.Type(), data)
584 }
585
586 return nil
587 }
588
589 func (d *Decoder) decodeInt(name string, data interface{}, val reflect.Value) error {
590 dataVal := reflect.Indirect(reflect.ValueOf(data))
591 dataKind := getKind(dataVal)
592 dataType := dataVal.Type()
593
594 switch {
595 case dataKind == reflect.Int:
596 val.SetInt(dataVal.Int())
597 case dataKind == reflect.Uint:
598 val.SetInt(int64(dataVal.Uint()))
599 case dataKind == reflect.Float32:
600 val.SetInt(int64(dataVal.Float()))
601 case dataKind == reflect.Bool && d.config.WeaklyTypedInput:
602 if dataVal.Bool() {
603 val.SetInt(1)
604 } else {
605 val.SetInt(0)
606 }
607 case dataKind == reflect.String && d.config.WeaklyTypedInput:
608 str := dataVal.String()
609 if str == "" {
610 str = "0"
611 }
612
613 i, err := strconv.ParseInt(str, 0, val.Type().Bits())
614 if err == nil {
615 val.SetInt(i)
616 } else {
617 return fmt.Errorf("cannot parse '%s' as int: %s", name, err)
618 }
619 case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number":
620 jn := data.(json.Number)
621 i, err := jn.Int64()
622 if err != nil {
623 return fmt.Errorf(
624 "error decoding json.Number into %s: %s", name, err)
625 }
626 val.SetInt(i)
627 default:
628 return fmt.Errorf(
629 "'%s' expected type '%s', got unconvertible type '%s', value: '%v'",
630 name, val.Type(), dataVal.Type(), data)
631 }
632
633 return nil
634 }
635
636 func (d *Decoder) decodeUint(name string, data interface{}, val reflect.Value) error {
637 dataVal := reflect.Indirect(reflect.ValueOf(data))
638 dataKind := getKind(dataVal)
639 dataType := dataVal.Type()
640
641 switch {
642 case dataKind == reflect.Int:
643 i := dataVal.Int()
644 if i < 0 && !d.config.WeaklyTypedInput {
645 return fmt.Errorf("cannot parse '%s', %d overflows uint",
646 name, i)
647 }
648 val.SetUint(uint64(i))
649 case dataKind == reflect.Uint:
650 val.SetUint(dataVal.Uint())
651 case dataKind == reflect.Float32:
652 f := dataVal.Float()
653 if f < 0 && !d.config.WeaklyTypedInput {
654 return fmt.Errorf("cannot parse '%s', %f overflows uint",
655 name, f)
656 }
657 val.SetUint(uint64(f))
658 case dataKind == reflect.Bool && d.config.WeaklyTypedInput:
659 if dataVal.Bool() {
660 val.SetUint(1)
661 } else {
662 val.SetUint(0)
663 }
664 case dataKind == reflect.String && d.config.WeaklyTypedInput:
665 str := dataVal.String()
666 if str == "" {
667 str = "0"
668 }
669
670 i, err := strconv.ParseUint(str, 0, val.Type().Bits())
671 if err == nil {
672 val.SetUint(i)
673 } else {
674 return fmt.Errorf("cannot parse '%s' as uint: %s", name, err)
675 }
676 case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number":
677 jn := data.(json.Number)
678 i, err := jn.Int64()
679 if err != nil {
680 return fmt.Errorf(
681 "error decoding json.Number into %s: %s", name, err)
682 }
683 if i < 0 && !d.config.WeaklyTypedInput {
684 return fmt.Errorf("cannot parse '%s', %d overflows uint",
685 name, i)
686 }
687 val.SetUint(uint64(i))
688 default:
689 return fmt.Errorf(
690 "'%s' expected type '%s', got unconvertible type '%s', value: '%v'",
691 name, val.Type(), dataVal.Type(), data)
692 }
693
694 return nil
695 }
696
697 func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) error {
698 dataVal := reflect.Indirect(reflect.ValueOf(data))
699 dataKind := getKind(dataVal)
700
701 switch {
702 case dataKind == reflect.Bool:
703 val.SetBool(dataVal.Bool())
704 case dataKind == reflect.Int && d.config.WeaklyTypedInput:
705 val.SetBool(dataVal.Int() != 0)
706 case dataKind == reflect.Uint && d.config.WeaklyTypedInput:
707 val.SetBool(dataVal.Uint() != 0)
708 case dataKind == reflect.Float32 && d.config.WeaklyTypedInput:
709 val.SetBool(dataVal.Float() != 0)
710 case dataKind == reflect.String && d.config.WeaklyTypedInput:
711 b, err := strconv.ParseBool(dataVal.String())
712 if err == nil {
713 val.SetBool(b)
714 } else if dataVal.String() == "" {
715 val.SetBool(false)
716 } else {
717 return fmt.Errorf("cannot parse '%s' as bool: %s", name, err)
718 }
719 default:
720 return fmt.Errorf(
721 "'%s' expected type '%s', got unconvertible type '%s', value: '%v'",
722 name, val.Type(), dataVal.Type(), data)
723 }
724
725 return nil
726 }
727
728 func (d *Decoder) decodeFloat(name string, data interface{}, val reflect.Value) error {
729 dataVal := reflect.Indirect(reflect.ValueOf(data))
730 dataKind := getKind(dataVal)
731 dataType := dataVal.Type()
732
733 switch {
734 case dataKind == reflect.Int:
735 val.SetFloat(float64(dataVal.Int()))
736 case dataKind == reflect.Uint:
737 val.SetFloat(float64(dataVal.Uint()))
738 case dataKind == reflect.Float32:
739 val.SetFloat(dataVal.Float())
740 case dataKind == reflect.Bool && d.config.WeaklyTypedInput:
741 if dataVal.Bool() {
742 val.SetFloat(1)
743 } else {
744 val.SetFloat(0)
745 }
746 case dataKind == reflect.String && d.config.WeaklyTypedInput:
747 str := dataVal.String()
748 if str == "" {
749 str = "0"
750 }
751
752 f, err := strconv.ParseFloat(str, val.Type().Bits())
753 if err == nil {
754 val.SetFloat(f)
755 } else {
756 return fmt.Errorf("cannot parse '%s' as float: %s", name, err)
757 }
758 case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number":
759 jn := data.(json.Number)
760 i, err := jn.Float64()
761 if err != nil {
762 return fmt.Errorf(
763 "error decoding json.Number into %s: %s", name, err)
764 }
765 val.SetFloat(i)
766 default:
767 return fmt.Errorf(
768 "'%s' expected type '%s', got unconvertible type '%s', value: '%v'",
769 name, val.Type(), dataVal.Type(), data)
770 }
771
772 return nil
773 }
774
775 func (d *Decoder) decodeMap(name string, data interface{}, val reflect.Value) error {
776 valType := val.Type()
777 valKeyType := valType.Key()
778 valElemType := valType.Elem()
779
780
781 valMap := val
782
783
784 if valMap.IsNil() || d.config.ZeroFields {
785
786 mapType := reflect.MapOf(valKeyType, valElemType)
787 valMap = reflect.MakeMap(mapType)
788 }
789
790
791 dataVal := reflect.Indirect(reflect.ValueOf(data))
792 switch dataVal.Kind() {
793 case reflect.Map:
794 return d.decodeMapFromMap(name, dataVal, val, valMap)
795
796 case reflect.Struct:
797 return d.decodeMapFromStruct(name, dataVal, val, valMap)
798
799 case reflect.Array, reflect.Slice:
800 if d.config.WeaklyTypedInput {
801 return d.decodeMapFromSlice(name, dataVal, val, valMap)
802 }
803
804 fallthrough
805
806 default:
807 return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind())
808 }
809 }
810
811 func (d *Decoder) decodeMapFromSlice(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error {
812
813 if dataVal.Len() == 0 {
814 val.Set(valMap)
815 return nil
816 }
817
818 for i := 0; i < dataVal.Len(); i++ {
819 err := d.decode(
820 name+"["+strconv.Itoa(i)+"]",
821 dataVal.Index(i).Interface(), val)
822 if err != nil {
823 return err
824 }
825 }
826
827 return nil
828 }
829
830 func (d *Decoder) decodeMapFromMap(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error {
831 valType := val.Type()
832 valKeyType := valType.Key()
833 valElemType := valType.Elem()
834
835
836 errors := make([]string, 0)
837
838
839 if dataVal.Len() == 0 {
840 if dataVal.IsNil() {
841 if !val.IsNil() {
842 val.Set(dataVal)
843 }
844 } else {
845
846 val.Set(valMap)
847 }
848
849 return nil
850 }
851
852 for _, k := range dataVal.MapKeys() {
853 fieldName := name + "[" + k.String() + "]"
854
855
856 currentKey := reflect.Indirect(reflect.New(valKeyType))
857 if err := d.decode(fieldName, k.Interface(), currentKey); err != nil {
858 errors = appendErrors(errors, err)
859 continue
860 }
861
862
863 v := dataVal.MapIndex(k).Interface()
864 currentVal := reflect.Indirect(reflect.New(valElemType))
865 if err := d.decode(fieldName, v, currentVal); err != nil {
866 errors = appendErrors(errors, err)
867 continue
868 }
869
870 valMap.SetMapIndex(currentKey, currentVal)
871 }
872
873
874 val.Set(valMap)
875
876
877 if len(errors) > 0 {
878 return &Error{errors}
879 }
880
881 return nil
882 }
883
884 func (d *Decoder) decodeMapFromStruct(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error {
885 typ := dataVal.Type()
886 for i := 0; i < typ.NumField(); i++ {
887
888
889 f := typ.Field(i)
890 if f.PkgPath != "" {
891 continue
892 }
893
894
895
896 v := dataVal.Field(i)
897 if !v.Type().AssignableTo(valMap.Type().Elem()) {
898 return fmt.Errorf("cannot assign type '%s' to map value field of type '%s'", v.Type(), valMap.Type().Elem())
899 }
900
901 tagValue := f.Tag.Get(d.config.TagName)
902 keyName := f.Name
903
904
905 squash := d.config.Squash && v.Kind() == reflect.Struct && f.Anonymous
906
907
908 if index := strings.Index(tagValue, ","); index != -1 {
909 if tagValue[:index] == "-" {
910 continue
911 }
912
913 if strings.Index(tagValue[index+1:], "omitempty") != -1 && isEmptyValue(v) {
914 continue
915 }
916
917
918 squash = !squash && strings.Index(tagValue[index+1:], "squash") != -1
919 if squash {
920
921 if v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct {
922 v = v.Elem()
923 }
924
925
926 if v.Kind() != reflect.Struct {
927 return fmt.Errorf("cannot squash non-struct type '%s'", v.Type())
928 }
929 }
930 keyName = tagValue[:index]
931 } else if len(tagValue) > 0 {
932 if tagValue == "-" {
933 continue
934 }
935 keyName = tagValue
936 }
937
938 switch v.Kind() {
939
940 case reflect.Struct:
941 x := reflect.New(v.Type())
942 x.Elem().Set(v)
943
944 vType := valMap.Type()
945 vKeyType := vType.Key()
946 vElemType := vType.Elem()
947 mType := reflect.MapOf(vKeyType, vElemType)
948 vMap := reflect.MakeMap(mType)
949
950
951
952
953
954 addrVal := reflect.New(vMap.Type())
955 reflect.Indirect(addrVal).Set(vMap)
956
957 err := d.decode(keyName, x.Interface(), reflect.Indirect(addrVal))
958 if err != nil {
959 return err
960 }
961
962
963
964 vMap = reflect.Indirect(addrVal)
965
966 if squash {
967 for _, k := range vMap.MapKeys() {
968 valMap.SetMapIndex(k, vMap.MapIndex(k))
969 }
970 } else {
971 valMap.SetMapIndex(reflect.ValueOf(keyName), vMap)
972 }
973
974 default:
975 valMap.SetMapIndex(reflect.ValueOf(keyName), v)
976 }
977 }
978
979 if val.CanAddr() {
980 val.Set(valMap)
981 }
982
983 return nil
984 }
985
986 func (d *Decoder) decodePtr(name string, data interface{}, val reflect.Value) (bool, error) {
987
988
989 isNil := data == nil
990 if !isNil {
991 switch v := reflect.Indirect(reflect.ValueOf(data)); v.Kind() {
992 case reflect.Chan,
993 reflect.Func,
994 reflect.Interface,
995 reflect.Map,
996 reflect.Ptr,
997 reflect.Slice:
998 isNil = v.IsNil()
999 }
1000 }
1001 if isNil {
1002 if !val.IsNil() && val.CanSet() {
1003 nilValue := reflect.New(val.Type()).Elem()
1004 val.Set(nilValue)
1005 }
1006
1007 return true, nil
1008 }
1009
1010
1011
1012 valType := val.Type()
1013 valElemType := valType.Elem()
1014 if val.CanSet() {
1015 realVal := val
1016 if realVal.IsNil() || d.config.ZeroFields {
1017 realVal = reflect.New(valElemType)
1018 }
1019
1020 if err := d.decode(name, data, reflect.Indirect(realVal)); err != nil {
1021 return false, err
1022 }
1023
1024 val.Set(realVal)
1025 } else {
1026 if err := d.decode(name, data, reflect.Indirect(val)); err != nil {
1027 return false, err
1028 }
1029 }
1030 return false, nil
1031 }
1032
1033 func (d *Decoder) decodeFunc(name string, data interface{}, val reflect.Value) error {
1034
1035
1036 dataVal := reflect.Indirect(reflect.ValueOf(data))
1037 if val.Type() != dataVal.Type() {
1038 return fmt.Errorf(
1039 "'%s' expected type '%s', got unconvertible type '%s', value: '%v'",
1040 name, val.Type(), dataVal.Type(), data)
1041 }
1042 val.Set(dataVal)
1043 return nil
1044 }
1045
1046 func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) error {
1047 dataVal := reflect.Indirect(reflect.ValueOf(data))
1048 dataValKind := dataVal.Kind()
1049 valType := val.Type()
1050 valElemType := valType.Elem()
1051 sliceType := reflect.SliceOf(valElemType)
1052
1053
1054 if dataValKind != reflect.Array && dataValKind != reflect.Slice {
1055 if d.config.WeaklyTypedInput {
1056 switch {
1057
1058 case dataValKind == reflect.Slice, dataValKind == reflect.Array:
1059 break
1060
1061
1062 case dataValKind == reflect.Map:
1063 if dataVal.Len() == 0 {
1064 val.Set(reflect.MakeSlice(sliceType, 0, 0))
1065 return nil
1066 }
1067
1068 return d.decodeSlice(name, []interface{}{data}, val)
1069
1070 case dataValKind == reflect.String && valElemType.Kind() == reflect.Uint8:
1071 return d.decodeSlice(name, []byte(dataVal.String()), val)
1072
1073
1074
1075 default:
1076
1077 return d.decodeSlice(name, []interface{}{data}, val)
1078 }
1079 }
1080
1081 return fmt.Errorf(
1082 "'%s': source data must be an array or slice, got %s", name, dataValKind)
1083 }
1084
1085
1086 if dataVal.IsNil() {
1087 return nil
1088 }
1089
1090 valSlice := val
1091 if valSlice.IsNil() || d.config.ZeroFields {
1092
1093 valSlice = reflect.MakeSlice(sliceType, dataVal.Len(), dataVal.Len())
1094 }
1095
1096
1097 errors := make([]string, 0)
1098
1099 for i := 0; i < dataVal.Len(); i++ {
1100 currentData := dataVal.Index(i).Interface()
1101 for valSlice.Len() <= i {
1102 valSlice = reflect.Append(valSlice, reflect.Zero(valElemType))
1103 }
1104 currentField := valSlice.Index(i)
1105
1106 fieldName := name + "[" + strconv.Itoa(i) + "]"
1107 if err := d.decode(fieldName, currentData, currentField); err != nil {
1108 errors = appendErrors(errors, err)
1109 }
1110 }
1111
1112
1113 val.Set(valSlice)
1114
1115
1116 if len(errors) > 0 {
1117 return &Error{errors}
1118 }
1119
1120 return nil
1121 }
1122
1123 func (d *Decoder) decodeArray(name string, data interface{}, val reflect.Value) error {
1124 dataVal := reflect.Indirect(reflect.ValueOf(data))
1125 dataValKind := dataVal.Kind()
1126 valType := val.Type()
1127 valElemType := valType.Elem()
1128 arrayType := reflect.ArrayOf(valType.Len(), valElemType)
1129
1130 valArray := val
1131
1132 if valArray.Interface() == reflect.Zero(valArray.Type()).Interface() || d.config.ZeroFields {
1133
1134 if dataValKind != reflect.Array && dataValKind != reflect.Slice {
1135 if d.config.WeaklyTypedInput {
1136 switch {
1137
1138 case dataValKind == reflect.Map:
1139 if dataVal.Len() == 0 {
1140 val.Set(reflect.Zero(arrayType))
1141 return nil
1142 }
1143
1144
1145
1146 default:
1147
1148 return d.decodeArray(name, []interface{}{data}, val)
1149 }
1150 }
1151
1152 return fmt.Errorf(
1153 "'%s': source data must be an array or slice, got %s", name, dataValKind)
1154
1155 }
1156 if dataVal.Len() > arrayType.Len() {
1157 return fmt.Errorf(
1158 "'%s': expected source data to have length less or equal to %d, got %d", name, arrayType.Len(), dataVal.Len())
1159
1160 }
1161
1162
1163 valArray = reflect.New(arrayType).Elem()
1164 }
1165
1166
1167 errors := make([]string, 0)
1168
1169 for i := 0; i < dataVal.Len(); i++ {
1170 currentData := dataVal.Index(i).Interface()
1171 currentField := valArray.Index(i)
1172
1173 fieldName := name + "[" + strconv.Itoa(i) + "]"
1174 if err := d.decode(fieldName, currentData, currentField); err != nil {
1175 errors = appendErrors(errors, err)
1176 }
1177 }
1178
1179
1180 val.Set(valArray)
1181
1182
1183 if len(errors) > 0 {
1184 return &Error{errors}
1185 }
1186
1187 return nil
1188 }
1189
1190 func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) error {
1191 dataVal := reflect.Indirect(reflect.ValueOf(data))
1192
1193
1194
1195 if dataVal.Type() == val.Type() {
1196 val.Set(dataVal)
1197 return nil
1198 }
1199
1200 dataValKind := dataVal.Kind()
1201 switch dataValKind {
1202 case reflect.Map:
1203 return d.decodeStructFromMap(name, dataVal, val)
1204
1205 case reflect.Struct:
1206
1207
1208
1209
1210
1211 mapType := reflect.TypeOf((map[string]interface{})(nil))
1212 mval := reflect.MakeMap(mapType)
1213
1214
1215
1216
1217
1218 addrVal := reflect.New(mval.Type())
1219
1220 reflect.Indirect(addrVal).Set(mval)
1221 if err := d.decodeMapFromStruct(name, dataVal, reflect.Indirect(addrVal), mval); err != nil {
1222 return err
1223 }
1224
1225 result := d.decodeStructFromMap(name, reflect.Indirect(addrVal), val)
1226 return result
1227
1228 default:
1229 return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind())
1230 }
1231 }
1232
1233 func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) error {
1234 dataValType := dataVal.Type()
1235 if kind := dataValType.Key().Kind(); kind != reflect.String && kind != reflect.Interface {
1236 return fmt.Errorf(
1237 "'%s' needs a map with string keys, has '%s' keys",
1238 name, dataValType.Key().Kind())
1239 }
1240
1241 dataValKeys := make(map[reflect.Value]struct{})
1242 dataValKeysUnused := make(map[interface{}]struct{})
1243 for _, dataValKey := range dataVal.MapKeys() {
1244 dataValKeys[dataValKey] = struct{}{}
1245 dataValKeysUnused[dataValKey.Interface()] = struct{}{}
1246 }
1247
1248 errors := make([]string, 0)
1249
1250
1251
1252
1253 structs := make([]reflect.Value, 1, 5)
1254 structs[0] = val
1255
1256
1257
1258 type field struct {
1259 field reflect.StructField
1260 val reflect.Value
1261 }
1262
1263
1264
1265 var remainField *field
1266
1267 fields := []field{}
1268 for len(structs) > 0 {
1269 structVal := structs[0]
1270 structs = structs[1:]
1271
1272 structType := structVal.Type()
1273
1274 for i := 0; i < structType.NumField(); i++ {
1275 fieldType := structType.Field(i)
1276 fieldVal := structVal.Field(i)
1277 if fieldVal.Kind() == reflect.Ptr && fieldVal.Elem().Kind() == reflect.Struct {
1278
1279 fieldVal = fieldVal.Elem()
1280 }
1281
1282
1283 squash := d.config.Squash && fieldVal.Kind() == reflect.Struct && fieldType.Anonymous
1284 remain := false
1285
1286
1287 tagParts := strings.Split(fieldType.Tag.Get(d.config.TagName), ",")
1288 for _, tag := range tagParts[1:] {
1289 if tag == "squash" {
1290 squash = true
1291 break
1292 }
1293
1294 if tag == "remain" {
1295 remain = true
1296 break
1297 }
1298 }
1299
1300 if squash {
1301 if fieldVal.Kind() != reflect.Struct {
1302 errors = appendErrors(errors,
1303 fmt.Errorf("%s: unsupported type for squash: %s", fieldType.Name, fieldVal.Kind()))
1304 } else {
1305 structs = append(structs, fieldVal)
1306 }
1307 continue
1308 }
1309
1310
1311 if remain {
1312 remainField = &field{fieldType, fieldVal}
1313 } else {
1314
1315 fields = append(fields, field{fieldType, fieldVal})
1316 }
1317 }
1318 }
1319
1320
1321 for _, f := range fields {
1322 field, fieldValue := f.field, f.val
1323 fieldName := field.Name
1324
1325 tagValue := field.Tag.Get(d.config.TagName)
1326 tagValue = strings.SplitN(tagValue, ",", 2)[0]
1327 if tagValue != "" {
1328 fieldName = tagValue
1329 }
1330
1331 rawMapKey := reflect.ValueOf(fieldName)
1332 rawMapVal := dataVal.MapIndex(rawMapKey)
1333 if !rawMapVal.IsValid() {
1334
1335
1336 for dataValKey := range dataValKeys {
1337 mK, ok := dataValKey.Interface().(string)
1338 if !ok {
1339
1340 continue
1341 }
1342
1343 if strings.EqualFold(mK, fieldName) {
1344 rawMapKey = dataValKey
1345 rawMapVal = dataVal.MapIndex(dataValKey)
1346 break
1347 }
1348 }
1349
1350 if !rawMapVal.IsValid() {
1351
1352
1353 continue
1354 }
1355 }
1356
1357 if !fieldValue.IsValid() {
1358
1359 panic("field is not valid")
1360 }
1361
1362
1363
1364 if !fieldValue.CanSet() {
1365 continue
1366 }
1367
1368
1369 delete(dataValKeysUnused, rawMapKey.Interface())
1370
1371
1372
1373 if name != "" {
1374 fieldName = name + "." + fieldName
1375 }
1376
1377 if err := d.decode(fieldName, rawMapVal.Interface(), fieldValue); err != nil {
1378 errors = appendErrors(errors, err)
1379 }
1380 }
1381
1382
1383
1384 if remainField != nil && len(dataValKeysUnused) > 0 {
1385
1386 remain := map[interface{}]interface{}{}
1387 for key := range dataValKeysUnused {
1388 remain[key] = dataVal.MapIndex(reflect.ValueOf(key)).Interface()
1389 }
1390
1391
1392 if err := d.decodeMap(name, remain, remainField.val); err != nil {
1393 errors = appendErrors(errors, err)
1394 }
1395
1396
1397
1398 dataValKeysUnused = nil
1399 }
1400
1401 if d.config.ErrorUnused && len(dataValKeysUnused) > 0 {
1402 keys := make([]string, 0, len(dataValKeysUnused))
1403 for rawKey := range dataValKeysUnused {
1404 keys = append(keys, rawKey.(string))
1405 }
1406 sort.Strings(keys)
1407
1408 err := fmt.Errorf("'%s' has invalid keys: %s", name, strings.Join(keys, ", "))
1409 errors = appendErrors(errors, err)
1410 }
1411
1412 if len(errors) > 0 {
1413 return &Error{errors}
1414 }
1415
1416
1417 if d.config.Metadata != nil {
1418 for rawKey := range dataValKeysUnused {
1419 key := rawKey.(string)
1420 if name != "" {
1421 key = name + "." + key
1422 }
1423
1424 d.config.Metadata.Unused = append(d.config.Metadata.Unused, key)
1425 }
1426 }
1427
1428 return nil
1429 }
1430
1431 func isEmptyValue(v reflect.Value) bool {
1432 switch getKind(v) {
1433 case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
1434 return v.Len() == 0
1435 case reflect.Bool:
1436 return !v.Bool()
1437 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
1438 return v.Int() == 0
1439 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
1440 return v.Uint() == 0
1441 case reflect.Float32, reflect.Float64:
1442 return v.Float() == 0
1443 case reflect.Interface, reflect.Ptr:
1444 return v.IsNil()
1445 }
1446 return false
1447 }
1448
1449 func getKind(val reflect.Value) reflect.Kind {
1450 kind := val.Kind()
1451
1452 switch {
1453 case kind >= reflect.Int && kind <= reflect.Int64:
1454 return reflect.Int
1455 case kind >= reflect.Uint && kind <= reflect.Uint64:
1456 return reflect.Uint
1457 case kind >= reflect.Float32 && kind <= reflect.Float64:
1458 return reflect.Float32
1459 default:
1460 return kind
1461 }
1462 }
1463
View as plain text