-
Notifications
You must be signed in to change notification settings - Fork 1
/
ref.go
111 lines (97 loc) · 1.98 KB
/
ref.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package ginplus
import (
"reflect"
"strings"
)
type (
Field struct {
Name string
Info []FieldInfo
}
FieldInfo struct {
Type string
Name string
Tags Tag
ChildType string
Info []FieldInfo
}
Tag struct {
FormKey string
UriKey string
Skip string
JsonKey string
Title string
Format string
Desc string
}
)
var tags = []string{"form", "uri", "json", "title", "format", "desc", "skip"}
// var 临时存储已经处理过的结构体
var tmpStruct = make(map[string]struct{})
// 获取结构体tag
func getTag(t reflect.Type) []FieldInfo {
if _, ok := tmpStruct[t.String()]; ok {
return nil
}
tmpStruct[t.String()] = struct{}{}
tmp := t
for tmp.Kind() == reflect.Ptr {
tmp = tmp.Elem()
}
if tmp.Kind() == reflect.Slice {
tmp = tmp.Elem()
for tmp.Kind() == reflect.Ptr {
tmp = tmp.Elem()
}
}
if tmp.Kind() != reflect.Struct {
return nil
}
fieldList := make([]FieldInfo, 0, tmp.NumField())
for i := 0; i < tmp.NumField(); i++ {
field := tmp.Field(i)
fieldName := field.Name
fieldType := field.Type.String()
tagInfo := Tag{
Title: fieldName,
}
for _, tagKey := range tags {
tagVal, ok := field.Tag.Lookup(tagKey)
if !ok {
continue
}
switch tagKey {
case "form":
tagInfo.FormKey = tagVal
case "uri":
tagInfo.UriKey = tagVal
case "skip":
tagInfo.Skip = tagVal
case "title":
tagInfo.Title = tagVal
case "format":
tagInfo.Format = tagVal
case "desc":
tagInfo.Desc = tagVal
default:
valList := strings.Split(tagVal, ",")
tagInfo.JsonKey = valList[0]
}
}
childType := field.Type
if childType.Kind() == reflect.Slice {
childType = childType.Elem()
for childType.Kind() == reflect.Ptr {
childType = childType.Elem()
}
}
fieldList = append(fieldList, FieldInfo{
Type: fieldType,
Name: fieldName,
Tags: tagInfo,
ChildType: childType.String(),
Info: getTag(childType),
})
}
return fieldList
}