-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmaps.go
64 lines (55 loc) · 1.17 KB
/
maps.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
package utils
import (
"encoding/gob"
"reflect"
"strconv"
)
func init() {
gob.Register([]M{})
gob.Register(M{})
}
type M map[string]interface{}
// convert map to struct
func (m M) MapToStruct(s interface{}) {
v := reflect.Indirect(reflect.ValueOf(s))
for i := 0; i < v.NumField(); i++ {
f := v.Type().Field(i)
key := f.Name
scnKey := Strings(key).SnakeCasedName()
tag := f.Tag
fieldName := tag.Get("field")
vf := v.Field(i)
doRes := false
if fieldName != "" {
if val, ok := m[fieldName]; ok {
vv := reflect.ValueOf(val)
if vf.Type().Kind().String() != vv.Type().Kind().String() {
if vf.Type().Kind().String() == "bool" {
if vv.Type().Kind().String() == "int64" && vv.Int() > 0 {
vf.SetBool(true)
}
if vv.Type().Kind().String() == "string" && vv.String() != "" {
ii, _ := strconv.ParseInt(vv.String(), 10, 64)
if ii > 0 {
vf.SetBool(true)
}
}
}
} else {
vf.Set(vv)
}
doRes = true
}
}
if !doRes {
if _, ok := m[key]; ok {
vf.Set(reflect.ValueOf(m[key]))
}
}
if !doRes {
if _, ok := m[scnKey]; ok {
vf.Set(reflect.ValueOf(m[scnKey]))
}
}
}
}