-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstruct_tags.go
More file actions
87 lines (74 loc) · 1.66 KB
/
struct_tags.go
File metadata and controls
87 lines (74 loc) · 1.66 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
84
85
86
87
package maml
import (
"reflect"
"strings"
"sync"
)
type fieldInfo struct {
name string // Go field name
mamlName string // key name in MAML
omitEmpty bool
ignore bool
index []int // field index for reflect
}
type structInfo struct {
fields []fieldInfo
}
var structCache sync.Map // map[reflect.Type]*structInfo
func getStructInfo(t reflect.Type) *structInfo {
if cached, ok := structCache.Load(t); ok {
return cached.(*structInfo)
}
info := buildStructInfo(t, nil)
structCache.Store(t, info)
return info
}
func buildStructInfo(t reflect.Type, parentIndex []int) *structInfo {
info := &structInfo{}
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if !f.IsExported() {
continue
}
index := make([]int, len(parentIndex)+1)
copy(index, parentIndex)
index[len(parentIndex)] = i
// Handle embedded structs
if f.Anonymous && f.Type.Kind() == reflect.Struct {
embedded := buildStructInfo(f.Type, index)
info.fields = append(info.fields, embedded.fields...)
continue
}
fi := fieldInfo{
name: f.Name,
index: index,
}
tag := f.Tag.Get("maml")
if tag == "" {
tag = f.Tag.Get("json")
}
if tag == "-" {
fi.ignore = true
fi.mamlName = f.Name
info.fields = append(info.fields, fi)
continue
}
if tag != "" {
parts := strings.Split(tag, ",")
if parts[0] != "" {
fi.mamlName = parts[0]
} else {
fi.mamlName = strings.ToLower(f.Name[:1]) + f.Name[1:]
}
for _, opt := range parts[1:] {
if opt == "omitempty" {
fi.omitEmpty = true
}
}
} else {
fi.mamlName = strings.ToLower(f.Name[:1]) + f.Name[1:]
}
info.fields = append(info.fields, fi)
}
return info
}