-
Notifications
You must be signed in to change notification settings - Fork 16
/
parse_match.go
222 lines (188 loc) · 5.23 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
package rux
import (
"regexp"
"strings"
)
/*************************************************************
* route parse
*************************************************************/
// 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
*************************************************************/
// Match route by given request METHOD and URI path
//
// ps - route path Params, when has path vars.
// alm - allowed request methods
func (r *Router) Match(method, path string) (route *Route, ps Params, alm []string) {
return r.QuickMatch(strings.ToUpper(method), path)
}
// QuickMatch match route by given request METHOD and URI path
// ps - route path Params, when has path vars.
// alm - allowed request methods
func (r *Router) QuickMatch(method, path string) (route *Route, ps Params, alm []string) {
if r.interceptAll != "" {
path = r.interceptAll
} else {
path = r.formatPath(path)
}
// do match route
if route, ps = r.match(method, path); route != nil {
return
}
// for HEAD requests, attempt fallback to GET
if method == HEAD {
route, ps = r.match(GET, path)
if route != nil {
return
}
}
// handle fallback route. add by: router->Any("/*", handler)
if r.handleFallbackRoute {
key := method + "/*"
if route, ok := r.stableRoutes[key]; ok {
return route, nil, nil
}
}
// handle method not allowed. will find allowed methods
if r.handleMethodNotAllowed {
alm = r.findAllowedMethods(method, path)
if len(alm) > 0 {
return
}
}
// don't handle method not allowed, will return not found
return
}
// func (r *Router) Search(method, path string) *Route {
// }
func (r *Router) match(method, path string) (rt *Route, ps Params) {
// find in stable routes
if route, ok := r.stableRoutes[method+path]; ok {
// return r.newMatchResult(route, nil)
return route, nil
}
// find in cached routes
if r.enableCaching {
route, ok := r.cachedRoutes.Get(method + path)
if ok {
return 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 i := range rs {
if strings.Index(path, rs[i].start) != 0 {
continue
}
if ps, ok := rs[i].matchRegex(path); ok {
// ret = r.newMatchResult(route, ps)
r.cacheDynamicRoute(key, ps, rs[i])
return rs[i], ps
}
}
}
}
// find in irregular routes
if rs, ok := r.irregularRoutes[method]; ok {
for _, route := range rs {
if ps, ok := route.matchRegex(path); ok {
r.cacheDynamicRoute(method+path, ps, route)
return route, ps
}
}
}
return
}
// cache dynamic Params route when EnableRouteCache is true
func (r *Router) cacheDynamicRoute(key string, ps Params, route *Route) {
if !r.enableCaching {
return
}
// 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 rt, _ := r.match(m, path); rt != nil {
mMap[m] = 1
}
}
if len(mMap) > 0 {
for m := range mMap {
allowed = append(allowed, m)
}
}
return
}