-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathparse_match.go
274 lines (229 loc) · 6.21 KB
/
parse_match.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
package rux
import (
"regexp"
"strings"
)
/*************************************************************
* route parse
*************************************************************/
const (
anyMatch = `[^/]+`
)
// "/users/{id}" "/users/{id:\d+}" `/users/{uid:\d+}/blog/{id}`
var varRegex = regexp.MustCompile(`{[^/]+}`)
// Parsing routes with parameters
func (r *Router) parseParamRoute(route *Route) (first string) {
path := route.path
// collect route Params
ss := varRegex.FindAllString(path, -1)
// no vars, but contains optional char
if len(ss) == 0 {
regexStr := checkAndParseOptional(quotePointChar(path))
route.regex = regexp.MustCompile("^" + regexStr + "$")
return
}
var n, v string
var rawVar, varRegex []string
for _, str := range ss {
nvStr := str[1 : len(str)-1] // "{level:[1-9]{1,2}}" -> "level:[1-9]{1,2}"
// eg "{uid:\d+}" -> "uid", "\d+"
if strings.IndexByte(nvStr, ':') > 0 {
nv := strings.SplitN(nvStr, ":", 2)
n, v = strings.TrimSpace(nv[0]), strings.TrimSpace(nv[1])
rawVar = append(rawVar, str, "{"+n+"}")
varRegex = append(varRegex, "{"+n+"}", "("+v+")")
} else {
n = nvStr // "{name}" -> "name"
v = getGlobalVar(n, anyMatch)
varRegex = append(varRegex, str, "("+v+")")
}
route.goodRegexString(n, v)
route.matches = append(route.matches, n)
}
// `/users/{uid:\d+}/blog/{id}` -> `/users/{uid}/blog/{id}`
if len(rawVar) > 0 {
path = strings.NewReplacer(rawVar...).Replace(path)
// save simple path
route.spath = path
}
// "." -> "\."
path = quotePointChar(path)
argPos := strings.IndexByte(path, '{')
optPos := strings.IndexByte(path, '[')
minPos := argPos
// has optional char. /blog[/{id}]
if optPos > 0 && argPos > optPos {
minPos = optPos
}
start := path[0:minPos]
if len(start) > 1 {
route.start = start
if pos := strings.IndexByte(start[1:], '/'); pos > 0 {
first = start[1 : pos+1]
// start string only one node. "/users/"
if len(start)-len(first) == 2 {
route.start = ""
}
}
}
// has optional char. /blog[/{id}] -> /blog(?:/{id})
if optPos > 0 {
path = checkAndParseOptional(path)
}
// replace {var} -> regex str
regexStr := strings.NewReplacer(varRegex...).Replace(path)
route.regex = regexp.MustCompile("^" + regexStr + "$")
return
}
/*************************************************************
* route match
*************************************************************/
// MatchResult for the route match
type MatchResult struct {
// Name current matched route name
Name string
// Path current matched route path rule
Path string
// Status match status: 1 found 2 not found 3 method not allowed
Status uint8
// Params route path Params, when Status = 1 and has path vars.
Params Params
// Handler the main handler for the route(Status = 1)
Handler HandlerFunc
// Handlers middleware handlers for the route(Status = 1)
Handlers HandlersChain
// AllowedMethods allowed request methods(Status = 3)
AllowedMethods []string
}
var notFoundResult = &MatchResult{Status: NotFound}
func newFoundResult(route *Route, ps Params) *MatchResult {
return &MatchResult{
Name: route.name,
Path: route.path,
Status: Found,
Params: ps,
Handler: route.handler,
Handlers: route.handlers,
}
}
// IsOK check status == Found ?
func (mr *MatchResult) IsOK() bool {
return mr.Status == Found
}
// Match route by given request METHOD and URI path
func (r *Router) Match(method, path string) (result *MatchResult) {
if r.interceptAll != "" {
path = r.interceptAll
}
path = r.formatPath(path)
method = strings.ToUpper(method)
// do match route
if result = r.match(method, path); result.IsOK() {
return
}
// for HEAD requests, attempt fallback to GET
if method == HEAD {
result = r.match(GET, path)
if result.Status == Found {
return
}
}
// if has fallback route. router->Any("/*", handler)
key := method + "/*"
if route, ok := r.stableRoutes[key]; ok {
return newFoundResult(route, nil)
}
// handle method not allowed. will find allowed methods
if r.handleMethodNotAllowed {
allowed := r.findAllowedMethods(method, path)
if len(allowed) > 0 {
result = &MatchResult{Status: NotAllowed, AllowedMethods: allowed}
}
}
// don't handle method not allowed, return not found
return
}
func (r *Router) match(method, path string) (ret *MatchResult) {
// find in stable routes
key := method + path
if route, ok := r.stableRoutes[key]; ok {
return newFoundResult(route, nil)
}
// find in cached routes
if r.enableCaching {
route, ok := r.cachedRoutes.Get(key)
if ok {
return newFoundResult(route, route.params)
}
}
// find in regular routes
if pos := strings.IndexByte(path[1:], '/'); pos > 0 {
key = method + path[1:pos+1]
if rs, ok := r.regularRoutes[key]; ok {
for _, route := range rs {
if strings.Index(path, route.start) != 0 {
continue
}
if ps, ok := route.matchRegex(path); ok {
ret = newFoundResult(route, ps)
r.cacheDynamicRoute(method, path, ps, route)
return
}
}
}
}
// find in irregular routes
if rs, ok := r.irregularRoutes[method]; ok {
for _, route := range rs {
if ps, ok := route.matchRegex(path); ok {
ret = newFoundResult(route, ps)
r.cacheDynamicRoute(method, path, ps, route)
return
}
}
}
return notFoundResult
}
// cache dynamic Params route when EnableRouteCache is true
func (r *Router) cacheDynamicRoute(method, path string, ps Params, route *Route) {
if !r.enableCaching {
return
}
// removed
// if r.cachedRoutes.Len() >= int(r.maxNumCaches) {
// num := 0
// maxClean := int(r.maxNumCaches / 10)
//
// for k := range r.cachedRoutes.Items() {
// if num == maxClean {
// break
// }
//
// num++
//
// r.cachedRoutes.Delete(k)
// }
// }
key := method + path
// copy new route instance. Notice: cache matched Params
r.cachedRoutes.Set(key, route.copyWithParams(ps))
}
// find allowed methods for current request
func (r *Router) findAllowedMethods(method, path string) (allowed []string) {
// use map for prevent duplication
mMap := map[string]int{}
for _, m := range anyMethods {
if m == method { // expected current method
continue
}
if r.match(m, path).IsOK() {
mMap[m] = 1
}
}
if len(mMap) > 0 {
for m := range mMap {
allowed = append(allowed, m)
}
}
return
}