-
Notifications
You must be signed in to change notification settings - Fork 3
/
get_type.go
52 lines (39 loc) · 819 Bytes
/
get_type.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
package reflectutils
import (
"reflect"
"strings"
)
// Get value of a struct by path using reflect.
func GetType(i interface{}, name string) (t reflect.Type) {
var err error
t = reflect.TypeOf(i)
if name == "" {
return
}
var token *dotToken
token, err = nextDot(name)
if err != nil {
return nil
}
if t.Kind() == reflect.Map || t.Kind() == reflect.Slice {
t = GetType(reflect.Zero(t.Elem()).Interface(), token.Left)
return
}
if t.Kind() != reflect.Struct {
for t.Elem().Kind() == reflect.Ptr {
t = t.Elem()
}
t = t.Elem()
}
if t.Kind() == reflect.Struct {
sf, ok := t.FieldByNameFunc(func(name string) bool {
return strings.EqualFold(name, token.Field)
})
if !ok {
return nil
}
t = GetType(reflect.Zero(sf.Type).Interface(), token.Left)
return
}
return
}