-
Notifications
You must be signed in to change notification settings - Fork 16
/
route.go
321 lines (269 loc) · 7.23 KB
/
route.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
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
package rux
import (
"fmt"
"net/url"
"regexp"
"strconv"
"strings"
"github.com/gookit/goutil"
)
/*************************************************************
* Route Params/Info
*************************************************************/
// RouteInfo simple route info struct
type RouteInfo struct {
Name, Path, HandlerName string
// supported method of the route
Methods []string
HandlerNum int
}
// Params for current route
type Params map[string]string
// Has param key in the Params
func (p Params) Has(key string) bool {
_, ok := p[key]
return ok
}
// String get string value by key
func (p Params) String(key string) (val string) {
if val, ok := p[key]; ok {
return val
}
return
}
// Int get int value by key
func (p Params) Int(key string) (val int) {
if str, ok := p[key]; ok {
val, err := strconv.Atoi(str)
if err == nil {
return val
}
}
return
}
/*************************************************************
* Route definition
*************************************************************/
// Route in the router
type Route struct {
// route name.
name string
// path for the route. eg "/users" "/users/{id}"
path string
// allowed methods
methods []string
// start string in the route path. "/users/{id}" -> "/user/"
start string
// path but no regex
// "/users/{uid:\d+}/blog/{id}" -> "/users/{uid}/blog/{id}"
spath string
// hosts []string
// regexp for the route path
regex *regexp.Regexp
// dynamic route param values, only use for route cache
params Params
// matched var names in the route path. eg "/api/{var1}/{var2}" -> [var1, var2]
matches []string
// the main handler for the route
handler HandlerFunc
// middleware handlers list for the route
handlers HandlersChain
// Opts some options data for the route
Opts map[string]any
// defaults
}
// NewRoute create a new route
func NewRoute(path string, handler HandlerFunc, methods ...string) *Route {
return &Route{
path: simpleFmtPath(path),
// handler
handler: handler,
methods: formatMethodsWithDefault(methods, GET),
// handlers: middleware,
}
}
// NamedRoute create a new route with name. alias of NewNamedRoute()
func NamedRoute(name, path string, handler HandlerFunc, methods ...string) *Route {
return NewNamedRoute(name, path, handler, methods...)
}
// NewNamedRoute create a new route with name
func NewNamedRoute(name, path string, handler HandlerFunc, methods ...string) *Route {
return &Route{
name: strings.TrimSpace(name),
path: simpleFmtPath(path),
// handler
handler: handler,
methods: formatMethodsWithDefault(methods, GET),
}
}
// Use add middleware handlers to the route
func (r *Route) Use(middleware ...HandlerFunc) *Route {
finalSize := len(r.handlers) + len(middleware)
if finalSize >= int(abortIndex) {
goutil.Panicf("too many handlers(number: %d)", finalSize)
}
r.handlers = append(r.handlers, middleware...)
return r
}
// AttachTo register the route to router.
func (r *Route) AttachTo(router *Router) {
router.AddRoute(r)
}
// NamedTo add name and register the route to router.
func (r *Route) NamedTo(name string, router *Router) {
if name = strings.TrimSpace(name); name != "" {
r.name = name
// attach to router
router.namedRoutes[name] = r
}
}
// Name get route name
func (r *Route) Name() string {
return r.name
}
// Path get route path string.
func (r *Route) Path() string {
return r.path
}
// Methods get route allowed request methods
func (r *Route) Methods() []string {
return r.methods
}
// MethodString join allowed methods to an string
func (r *Route) MethodString(char string) string {
return strings.Join(r.methods, char)
}
// Handler returns the main handler.
func (r *Route) Handler() HandlerFunc {
return r.handler
}
// Handlers returns handlers of the route.
func (r *Route) Handlers() HandlersChain {
return r.handlers
}
// HandlerName get the main handler name
func (r *Route) HandlerName() string {
return goutil.FuncName(r.handler)
}
// String route info to string
func (r *Route) String() string {
method := r.MethodString(",")
template := "%-15s %-38s --> %s (%d middleware)"
// will print two line
if len(method) > 14 {
method = method + "\n" + strings.Repeat(" ", 27)
template = "%s %-38s --> %s (%d middleware)"
}
return fmt.Sprintf(template, method, r.path, r.HandlerName(), len(r.handlers))
}
// Info get basic info of the route
func (r *Route) Info() RouteInfo {
return RouteInfo{r.name, r.path, r.HandlerName(), r.methods, len(r.handlers)}
}
// ToURL build request URL, can with path vars
func (r *Route) ToURL(buildArgs ...any) *url.URL {
var URLBuilder *BuildRequestURL
//noinspection GoNilness
path := r.path
vlen := len(buildArgs)
if vlen == 0 {
return NewBuildRequestURL().Path(path).Build()
}
var withParams = make(M)
if vlen == 1 {
switch buildArgs[0].(type) {
case *BuildRequestURL:
URLBuilder = buildArgs[0].(*BuildRequestURL)
case M:
URLBuilder = NewBuildRequestURL()
withParams = buildArgs[0].(M)
default:
panic("buildArgs odd argument count")
}
} else { // vlen > 1
if vlen%2 == 1 {
panic("buildArgs odd argument count")
}
for i := 0; i < len(buildArgs); i += 2 {
withParams[goutil.String(buildArgs[i])] = buildArgs[i+1]
}
URLBuilder = NewBuildRequestURL()
}
return URLBuilder.Path(path).Build(withParams)
}
// BuildRequestURL alias of the method BuildRequestURL()
func (r *Router) BuildRequestURL(name string, buildArgs ...any) *url.URL {
return r.BuildURL(name, buildArgs...)
}
// BuildURL build Request URL one arg can be set buildRequestURL or rux.M
func (r *Router) BuildURL(name string, buildArgs ...any) *url.URL {
route := r.GetRoute(name)
if route == nil {
goutil.Panicf("BuildRequestURL get route is nil(name: %s)", name)
}
//noinspection GoNilness
return route.ToURL(buildArgs...)
}
// check route info
func (r *Route) goodInfo() {
if r.handler == nil {
goutil.Panicf("the route handler cannot be empty.(path: '%s')", r.path)
}
if len(r.methods) == 0 {
goutil.Panicf("the route allowed methods cannot be empty.(path: '%s')", r.path)
}
str := MethodsString()
for _, method := range r.methods {
if strings.Index(","+str, ","+method) == -1 {
goutil.Panicf("invalid method name '%s', must in: %s", method, str)
}
}
}
// check custom var regex string.
// ERROR:
//
// "{id:(\d+)}" -> "(\d+)"
//
// RIGHT:
//
// "{id:\d+}"
// "{id:(?:\d+)}"
func (r *Route) goodRegexString(n, v string) {
pos := strings.IndexByte(v, '(')
if pos != -1 && pos < len(v) && v[pos+1] != '?' {
goutil.Panicf("invalid path var regex string, dont allow char '('. var: %s, regex: %s", n, v)
}
}
// check start string and match a regex route
func (r *Route) match(path string) (ps Params, ok bool) {
// check start string
if r.start != "" && strings.Index(path, r.start) != 0 {
return
}
return r.matchRegex(path)
}
// match a regex route
func (r *Route) matchRegex(path string) (ps Params, ok bool) {
// regex match
ss := r.regex.FindAllStringSubmatch(path, -1)
if len(ss) == 0 {
return
}
ok = true
vs := ss[0]
ps = make(Params, len(vs))
// Notice: vs[0] is full path.
for i, val := range vs[1:] {
// n := r.matches[i]
ps[r.matches[i]] = val
}
return
}
// copy a new instance
func (r *Route) copyWithParams(ps Params) *Route {
var nr = *r
nr.regex = nil
nr.matches = nil
nr.params = ps
return &nr
}