-
Notifications
You must be signed in to change notification settings - Fork 11
/
structs.go
88 lines (78 loc) · 1.82 KB
/
structs.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package json
import (
"fmt"
"reflect"
"strings"
"unicode"
tmsync "github.com/consideritdone/landslidecore/libs/sync"
)
var (
// cache caches struct info.
cache = newStructInfoCache()
)
// structCache is a cache of struct info.
type structInfoCache struct {
tmsync.RWMutex
structInfos map[reflect.Type]*structInfo
}
func newStructInfoCache() *structInfoCache {
return &structInfoCache{
structInfos: make(map[reflect.Type]*structInfo),
}
}
func (c *structInfoCache) get(rt reflect.Type) *structInfo {
c.RLock()
defer c.RUnlock()
return c.structInfos[rt]
}
func (c *structInfoCache) set(rt reflect.Type, sInfo *structInfo) {
c.Lock()
defer c.Unlock()
c.structInfos[rt] = sInfo
}
// structInfo contains JSON info for a struct.
type structInfo struct {
fields []*fieldInfo
}
// fieldInfo contains JSON info for a struct field.
type fieldInfo struct {
jsonName string
omitEmpty bool
hidden bool
}
// makeStructInfo generates structInfo for a struct as a reflect.Value.
func makeStructInfo(rt reflect.Type) *structInfo {
if rt.Kind() != reflect.Struct {
panic(fmt.Sprintf("can't make struct info for non-struct value %v", rt))
}
if sInfo := cache.get(rt); sInfo != nil {
return sInfo
}
fields := make([]*fieldInfo, 0, rt.NumField())
for i := 0; i < cap(fields); i++ {
frt := rt.Field(i)
fInfo := &fieldInfo{
jsonName: frt.Name,
omitEmpty: false,
hidden: frt.Name == "" || !unicode.IsUpper(rune(frt.Name[0])),
}
o := frt.Tag.Get("json")
if o == "-" {
fInfo.hidden = true
} else if o != "" {
opts := strings.Split(o, ",")
if opts[0] != "" {
fInfo.jsonName = opts[0]
}
for _, o := range opts[1:] {
if o == "omitempty" {
fInfo.omitEmpty = true
}
}
}
fields = append(fields, fInfo)
}
sInfo := &structInfo{fields: fields}
cache.set(rt, sInfo)
return sInfo
}