-
Notifications
You must be signed in to change notification settings - Fork 0
/
structs_map.go
53 lines (51 loc) · 1.06 KB
/
structs_map.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
package structs
import (
"github.com/go-xe2/x/type/xstring"
"reflect"
)
func MapField(structPtr interface{}, priority []string, recursive bool) (map[string]IField, error) {
result := make(map[string]IField)
obj, err := New(structPtr)
if err != nil {
return nil, err
}
fields := obj.Fields()
var fieldName = ""
var fieldTag = ""
for _, field := range fields {
fieldName = field.Name()
if xstring.IsFirstLetterLower(fieldName) {
continue
}
result[fieldName] = field
fieldTag = ""
tags := field.Tag()
for _, p := range priority {
fieldTag = tags.Get(p).Value()
if fieldTag != "" && fieldTag != "-" {
break
}
}
result[fieldTag] = field
if recursive {
rv := reflect.ValueOf(field.Type())
kind := rv.Kind()
if kind == reflect.Ptr {
rv = rv.Elem()
kind = rv.Kind()
}
if kind == reflect.Struct {
mFields, err := MapField(rv, priority, true)
if err != nil {
continue
}
for k, v := range mFields {
if _, ok := result[k]; !ok {
result[k] = v
}
}
}
}
}
return result, nil
}