-
Notifications
You must be signed in to change notification settings - Fork 3
/
struct.go
72 lines (60 loc) · 1.7 KB
/
struct.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package convert
import (
"reflect"
"fmt"
"strings"
)
func (stdRecipes) nilToStruct(Converter, NilValue, StructValue) error {
return nil
}
func (stdRecipes) mapToStruct(c Converter, in MapValue, out StructValue) error {
fieldNameValue := reflect.New(reflect.TypeOf(""))
for _, key := range in.MapKeys() {
// convert key
if err := c.ConvertReflectValue(key, fieldNameValue); err != nil {
return err
}
fieldName := fieldNameValue.Elem().String()
// find the destination field with the converted value
field := out.Elem().FieldByNameFunc(func(s string) bool {
return strings.EqualFold(fieldName, s)
})
if !field.IsValid() || !field.CanSet() {
if c.Options().SkipUnknownFields {
continue
}
return fmt.Errorf("unable to find %s in %s", fieldName, out.Elem().Type().String())
}
// convert value
value := reflect.New(field.Type())
if err := c.ConvertReflectValue(in.MapIndex(key), value); err != nil {
return err
}
field.Set(value.Elem())
}
return nil
}
func (stdRecipes) structToStruct(c Converter, in, out StructValue) error {
for i := in.NumField() - 1; i >= 0; i-- {
fieldName := in.Type().Field(i).Name
// find the destination field
// find the destination field with the converted value
field := out.Elem().FieldByNameFunc(func(s string) bool {
return strings.EqualFold(fieldName, s)
})
if !field.IsValid() || !field.CanSet() {
if c.Options().SkipUnknownFields {
continue
}
return fmt.Errorf("unable to find %s in %s", fieldName, out.Elem().Type().String())
}
// convert value
value := reflect.New(field.Type())
err := c.ConvertReflectValue(in.Field(i), value)
if err != nil {
return err
}
field.Set(value.Elem())
}
return nil
}