-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.go
More file actions
93 lines (77 loc) · 1.78 KB
/
cache.go
File metadata and controls
93 lines (77 loc) · 1.78 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
88
89
90
91
92
93
package qparser
import (
"reflect"
"sync"
"time"
)
var structCache sync.Map
type structInfo struct {
name string
fields []fieldInfo
hasUnexportedWithTag bool
}
type fieldInfo struct {
name string
tag string
typ reflect.Type
index []int
isNested bool
}
func getStructCache(rt reflect.Type) *structInfo {
// Try to load from cache
if cached, ok := structCache.Load(rt); ok {
return cached.(*structInfo)
}
// Build struct info
info := &structInfo{name: rt.Name()}
// struct fields traversal
for i := 0; i < rt.NumField(); i++ {
field := rt.Field(i)
tag := field.Tag.Get("qp")
fieldType := field.Type
if fieldType.Kind() == reflect.Ptr {
fieldType = fieldType.Elem()
}
isStruct := fieldType.Kind() == reflect.Struct && fieldType != reflect.TypeFor[time.Time]()
// traverse embedded structs
if field.Anonymous && isStruct {
info.fields = append(info.fields, fieldInfo{
name: field.Name,
typ: field.Type,
index: field.Index,
isNested: true,
})
continue
}
if !field.IsExported() {
if tag != "" {
info.hasUnexportedWithTag = true
}
continue
}
// tag on struct will be ignored
if isStruct {
info.fields = append(info.fields, fieldInfo{
name: field.Name,
typ: field.Type,
index: field.Index,
isNested: true,
})
continue
}
// leaf field
if tag != "" {
info.fields = append(info.fields, fieldInfo{
name: field.Name,
tag: tag,
typ: field.Type,
index: field.Index,
isNested: false,
})
}
}
// LoadOrStore handles race conditions atomically
// If another goroutine stored a value first, we return that instead
actual, _ := structCache.LoadOrStore(rt, info)
return actual.(*structInfo)
}