forked from xs23933/web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.go
61 lines (53 loc) · 1.39 KB
/
router.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
package web
import (
"regexp"
"strings"
)
// Route 路由
type Route struct {
isGet bool // allows head requests if get
isMiddleware bool // is middleware route
isStar bool // path == "*"
isSlash bool // path == "/"
isRegex bool // needs regex parsing
Method string // http method
Path string // original path
Params []string // path params
Regexp *regexp.Regexp // regexp matcher
Handler func(*Ctx) // ctx handler
}
func (r *Route) matchRoute(method, path string) (match bool, values []string) {
if r.isMiddleware {
if r.isStar || r.isSlash {
return true, values
}
if strings.HasPrefix(path, r.Path) {
return true, values
}
// middlewares dont support regex so bye
return false, values
}
if r.Method == method || r.Method[0] == '*' || (r.isGet && len(method) == 4 && method == "HEAD") {
if r.isStar { // '*' means we match anything
return true, values
}
if r.isSlash && path == "/" { // simple '/' bool
return true, values
}
if r.isRegex && r.Regexp.MatchString(path) {
if len(r.Params) > 0 {
matches := r.Regexp.FindAllStringSubmatch(path, -1)
if len(matches) > 0 && len(matches[0]) > 1 {
values = matches[0][1:len(matches[0])]
return true, values
}
return false, values
}
return true, values
}
if len(r.Path) == len(path) && r.Path == path {
return true, values
}
}
return false, values
}