-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstruct.go
More file actions
83 lines (65 loc) · 1.48 KB
/
struct.go
File metadata and controls
83 lines (65 loc) · 1.48 KB
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
78
79
80
81
82
83
package flagstruct
import "reflect"
// fieldData contains StructField and Value of a property,
// that extracted from input struct
type fieldData struct {
field reflect.StructField
value reflect.Value
tag *tagData
}
// structVal returns reflect.Value of struct
func structVal(i interface{}) reflect.Value {
v := reflect.ValueOf(i)
// if pointer get the underlying element≤
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Kind() != reflect.Struct {
panic("not struct")
}
return v
}
// structFields returns list of field and data which have tag flag
func structFields(i interface{}) []fieldData {
sv := structVal(i)
return getFields(sv)
}
func getFields(v reflect.Value) []fieldData {
var f []fieldData
t := v.Type()
for i := 0; i < t.NumField(); i = i + 1 {
field := t.Field(i)
if field.Anonymous {
av := v.FieldByName(field.Name)
if av.Kind() == reflect.Ptr {
av = av.Elem()
}
if av.IsValid() == false {
continue
}
if fields := getFields(av); len(fields) > 0 {
f = append(f, fields...)
}
continue
}
if td := parseTag(field); td != nil {
fd := fieldData{
field: field,
value: v.FieldByName(field.Name),
tag: td,
}
f = append(f, fd)
}
}
return f
}
// isStructPointer returns true if the given interface is a pointer to a struct.
func isStructPointer(s interface{}) bool {
v := reflect.ValueOf(s)
if v.Kind() == reflect.Ptr {
v = v.Elem()
} else {
return false
}
return v.Kind() == reflect.Struct
}