-
Notifications
You must be signed in to change notification settings - Fork 34
/
route.go
56 lines (45 loc) · 1.06 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
package traffic
import (
"net/url"
"regexp"
)
type Route struct {
Path string
PathRegexp *regexp.Regexp
IsStatic bool
Handlers []HttpHandleFunc
beforeFilters []HttpHandleFunc
}
func (route *Route) AddBeforeFilter(beforeFilters ...HttpHandleFunc) *Route {
route.beforeFilters = append(route.beforeFilters, beforeFilters...)
return route
}
func NewRoute(path string, handlers ...HttpHandleFunc) *Route {
regexp, isStatic := pathToRegexp(path)
route := &Route{
Path: path,
PathRegexp: regexp,
IsStatic: isStatic,
Handlers: handlers,
}
return route
}
func (route Route) Match(path string) (url.Values, bool) {
values := make(url.Values)
if route.IsStatic {
return values, route.Path == path
}
matches := route.PathRegexp.FindAllStringSubmatch(path, -1)
if matches != nil {
names := route.PathRegexp.SubexpNames()
for i := 1; i < len(names); i++ {
name := names[i]
value := matches[0][i]
if len(name) > 0 && len(value) > 0 {
values.Set(name, value)
}
}
return values, true
}
return values, false
}