-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmethod.go
More file actions
277 lines (267 loc) · 6.63 KB
/
method.go
File metadata and controls
277 lines (267 loc) · 6.63 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
package restruct
import (
"context"
"mime/multipart"
"net/http"
"reflect"
"runtime"
"strings"
"unicode"
)
var (
typeHttpRequest = reflect.TypeOf(&http.Request{})
typeHttpWriter = reflect.TypeOf((*http.ResponseWriter)(nil)).Elem()
typeContext = reflect.TypeOf((*context.Context)(nil)).Elem()
typeError = reflect.TypeOf((*error)(nil)).Elem()
typeInt = reflect.TypeOf((*int)(nil)).Elem()
typeMultipartFileHeader = reflect.TypeOf(&multipart.FileHeader{})
typeMultipartFileHeaderSlice = reflect.TypeOf([]*multipart.FileHeader{})
)
type (
method struct {
Name string
location string
source reflect.Value
path string
pathParts []string
params []reflect.Type
returns []reflect.Type
methods map[string]bool
middlewares []Middleware
writer ResponseWriter
readerTypes []reflect.Type // Pre-computed types for RequestReader
readerIndexes []int // Pre-computed indexes for RequestReader args
}
)
// returns methods from structs and nested structs
func serviceToMethods(prefix string, svc interface{}) (methods []*method) {
tv := reflect.TypeOf(svc)
vv := reflect.ValueOf(svc)
// get methods first
routes := make(map[string][]Route)
skipMethods := map[string]bool{}
if _, ok := svc.(Init); ok {
skipMethods["Init"] = true
}
var middlewares []Middleware
if mws, ok := svc.(Middlewares); ok {
middlewares = mws.Middlewares()
skipMethods["Middlewares"] = true
}
// Check for Writer
var writer ResponseWriter
if v, ok := svc.(Writer); ok {
writer = v.Writer()
skipMethods["Writer"] = true
}
var funcMethods []*method
if router, ok := svc.(Router); ok {
for _, route := range router.Routes() {
switch h := route.Handler.(type) {
case string:
routes[h] = append(routes[h], route)
default:
rv := reflect.ValueOf(h)
if rv.Kind() != reflect.Func {
panic("Route.Handler must be a string or func")
}
loc := runtime.FuncForPC(rv.Pointer()).Name()
m := &method{
Name: loc,
location: loc,
source: rv,
middlewares: middlewares,
writer: writer,
}
m.middlewares = append(m.middlewares, route.Middlewares...)
if route.Path != "" {
if route.Path == "." {
m.path = strings.TrimRight(prefix, "/")
} else {
m.path = prefix + strings.TrimLeft(route.Path, "/")
}
}
if len(route.Methods) > 0 {
m.methods = make(map[string]bool)
for _, method := range route.Methods {
m.methods[method] = true
}
}
m.mustParse()
funcMethods = append(funcMethods, m)
}
}
skipMethods["Routes"] = true
}
tvt := vv.NumMethod()
tvEl := tv
if tv.Kind() == reflect.Ptr {
tvEl = tv.Elem()
}
location := tvEl.PkgPath() + "." + tvEl.Name()
for i := 0; i < tvt; i++ {
m := tv.Method(i)
// Skip interface methods
if _, ok := skipMethods[m.Name]; ok {
continue
}
mm := &method{
Name: m.Name,
location: location + "." + m.Name,
source: vv.Method(i),
middlewares: middlewares,
writer: writer,
}
if len(routes) > 0 {
rts, ok := routes[m.Name]
if ok {
for _, route := range rts {
mr := &method{
Name: mm.Name,
location: mm.location,
source: mm.source,
middlewares: mm.middlewares,
writer: mm.writer,
}
mr.middlewares = append(mr.middlewares, route.Middlewares...)
if route.Path != "" {
if route.Path == "." {
mr.path = strings.TrimRight(prefix, "/")
} else {
mr.path = prefix + strings.TrimLeft(route.Path, "/")
}
} else {
mr.path = prefix + nameToPath(m.Name)
}
if len(route.Methods) > 0 {
mr.methods = make(map[string]bool)
for _, method := range route.Methods {
mr.methods[method] = true
}
}
mr.mustParse()
methods = append(methods, mr)
}
continue
}
}
mm.path = prefix + nameToPath(m.Name)
mm.mustParse()
methods = append(methods, mm)
}
if tv.Kind() == reflect.Ptr {
tv = tv.Elem()
vv = vv.Elem()
}
// check fields
tvt = vv.NumField()
for i := 0; i < tvt; i++ {
f := tv.Field(i)
if f.PkgPath != "" {
continue
}
route := f.Tag.Get("route")
if route != "-" {
fk := f.Type.Kind()
fv := vv.Field(i)
if fk == reflect.Ptr {
fk = f.Type.Elem().Kind()
fv = fv.Elem()
}
if fk == reflect.Struct && fv.IsValid() {
if route == "" {
route = nameToPath(f.Name)
}
route = strings.Trim(route, "/") + "/"
sv := fv.Addr().Interface()
methods = append(methods, serviceToMethods(prefix+route, sv)...)
}
}
}
methods = append(methods, funcMethods...)
return
}
// Converts a Name into a path route like:
// HelloWorld -> hello-world
// Hello_World -> hello_world
// Hello_0 -> hello/{0}
// Hello_0_World -> hello/{0}/world
func nameToPath(name string) string {
var buf strings.Builder
nt := len(name)
if name == "Index" {
return ""
}
if name == "Any" {
return "{any*}"
}
if strings.HasSuffix(name, "_Any") {
return nameToPath(strings.TrimSuffix(name, "_Any")) + "/{any*}"
}
skipDash := false
startParam := false
for i := 0; i < nt; i++ {
c := rune(name[i])
if !startParam && unicode.IsUpper(c) {
if i > 0 && !skipDash {
buf.WriteByte('-')
}
c = unicode.ToLower(c)
buf.WriteRune(c)
skipDash = false
} else if c == '_' {
if startParam {
buf.WriteByte('}')
startParam = false
}
buf.WriteByte('/')
skipDash = true
} else {
if !startParam && skipDash && unicode.IsNumber(c) {
startParam = true
buf.WriteString("{")
buf.WriteRune(c)
} else {
buf.WriteRune(c)
}
if !startParam {
skipDash = false
}
}
}
if startParam {
buf.WriteByte('}')
}
return buf.String()
}
// Populates method fields, if there's no params it will leave pathRe nil and
// directly compare path with equality.
func (m *method) mustParse() {
m.pathParts = make([]string, 0)
for _, p := range strings.Split(m.path, "/") {
if p != "" {
m.pathParts = append(m.pathParts, p)
}
}
if m.source.IsValid() {
mt := m.source.Type()
if mt.Kind() != reflect.Func {
panic("method must be of type func")
}
for i := 0; i < mt.NumOut(); i++ {
m.returns = append(m.returns, mt.Out(i))
}
for i := 0; i < mt.NumIn(); i++ {
t := mt.In(i)
m.params = append(m.params, t)
// Pre-compute which params need RequestReader
switch t {
case typeHttpRequest, typeHttpWriter, typeContext:
// These are handled directly, not via RequestReader
default:
m.readerTypes = append(m.readerTypes, t)
m.readerIndexes = append(m.readerIndexes, i)
}
}
}
}