-
Notifications
You must be signed in to change notification settings - Fork 2
/
reflect.go
69 lines (55 loc) · 1.5 KB
/
reflect.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
package config
import (
"fmt"
"reflect"
)
type ReflectField struct {
Field reflect.Value
FieldType reflect.StructField
}
func getExportedFields(obj interface{}) ([]*ReflectField, error) {
objValue, objType, err := getIndirect(obj)
if err != nil {
return nil, err
}
return getExportedFieldsStruct(objValue, objType)
}
func getExportedFieldsStruct(objValue reflect.Value, objType reflect.Type) ([]*ReflectField, error) {
if objType.Kind() != reflect.Struct {
return nil, fmt.Errorf(
"invalid type embedded type in configuration struct",
)
}
fields := []*ReflectField{}
for i := 0; i < objType.NumField(); i++ {
field := objValue.Field(i)
fieldType := objType.Field(i)
if fieldType.Anonymous {
embeddedFields, err := getExportedFieldsStruct(field, fieldType.Type)
if err != nil {
return nil, err
}
fields = append(fields, embeddedFields...)
continue
}
if !isExported(fieldType.Name) {
continue
}
fields = append(fields, &ReflectField{
Field: field,
FieldType: fieldType,
})
}
return fields, nil
}
func getIndirect(obj interface{}) (reflect.Value, reflect.Type, error) {
indirect := reflect.Indirect(reflect.ValueOf(obj))
if !indirect.IsValid() {
return reflect.Value{}, nil, fmt.Errorf("configuration target is not a pointer to struct")
}
indirectType := indirect.Type()
if indirectType.Kind() != reflect.Struct {
return reflect.Value{}, nil, fmt.Errorf("configuration target is not a pointer to struct")
}
return indirect, indirectType, nil
}