/
get.go
77 lines (59 loc) · 1.21 KB
/
get.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
73
74
75
76
77
package utils
import (
"github.com/iwind/TeaGo/types"
"reflect"
"regexp"
)
var RegexpDigitNumber = regexp.MustCompile(`^\d+$`)
func Get(object interface{}, keys []string) interface{} {
if len(keys) == 0 {
return object
}
if object == nil {
return nil
}
firstKey := keys[0]
keys = keys[1:]
value := reflect.ValueOf(object)
if !value.IsValid() {
return nil
}
if value.Kind() == reflect.Ptr {
value = value.Elem()
}
if value.Kind() == reflect.Struct {
field := value.FieldByName(firstKey)
if !field.IsValid() {
return nil
}
if len(keys) == 0 {
return field.Interface()
}
return Get(field.Interface(), keys)
}
if value.Kind() == reflect.Map {
mapKey := reflect.ValueOf(firstKey)
mapValue := value.MapIndex(mapKey)
if !mapValue.IsValid() {
return nil
}
if len(keys) == 0 {
return mapValue.Interface()
}
return Get(mapValue.Interface(), keys)
}
if value.Kind() == reflect.Slice {
if RegexpDigitNumber.MatchString(firstKey) {
firstKeyInt := types.Int(firstKey)
if value.Len() > firstKeyInt {
result := value.Index(firstKeyInt).Interface()
if len(keys) == 0 {
return result
}
return Get(result, keys)
}
}
return nil
}
return nil
}