-
Notifications
You must be signed in to change notification settings - Fork 0
/
structlayout.go
78 lines (60 loc) · 1.51 KB
/
structlayout.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
package structscanner
import (
"database/sql"
"reflect"
"sync"
"time"
)
var cachedLayouts = &sync.Map{}
type structLayout struct {
fields []field
fieldsByName map[string]*field
}
func findStructFields(t reflect.Type, parentPath string, parentFieldIndex []int, fields *[]field) {
isPtr := t.Kind() == reflect.Ptr
if isPtr {
t = t.Elem()
}
fieldCount := t.NumField()
scannerInterface := reflect.TypeOf((*sql.Scanner)(nil)).Elem()
timeType := reflect.TypeOf((*time.Time)(nil)).Elem()
for i := 0; i < fieldCount; i++ {
f := t.Field(i)
tag := f.Tag.Get("db")
if tag == "" {
continue
}
fieldPath := tag
if parentPath != "" {
fieldPath = parentPath + "." + fieldPath
}
fieldIndex := make([]int, len(parentFieldIndex)+1)
copy(fieldIndex, parentFieldIndex)
fieldIndex[len(fieldIndex)-1] = f.Index[0]
fieldType := f.Type
if fieldType.Kind() == reflect.Ptr {
fieldType = fieldType.Elem()
}
if fieldType.Kind() == reflect.Struct &&
!reflect.PtrTo(fieldType).Implements(scannerInterface) &&
fieldType != timeType {
findStructFields(f.Type, fieldPath, fieldIndex, fields)
} else {
*fields = append(*fields, field{
Name: fieldPath,
Type: fieldType,
Indices: fieldIndex,
})
}
}
}
func newStructLayout(sType reflect.Type) *structLayout {
sl := &structLayout{
fieldsByName: make(map[string]*field),
}
findStructFields(sType, "", nil, &sl.fields)
for i := range sl.fields {
sl.fieldsByName[sl.fields[i].Name] = &sl.fields[i]
}
return sl
}