-
Notifications
You must be signed in to change notification settings - Fork 0
/
routetable.go
69 lines (60 loc) · 1.55 KB
/
routetable.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
package mano
import (
"container/list"
"net/url"
"regexp"
"github.com/junhwong/mano/logs"
)
type RouteData struct {
entry *RouteEntry
matchedUrl string
values map[string]string
}
type RouteEntry struct {
method HttpMethod
pattern *regexp.Regexp
handler HandlerFunc
middlewares []Middleware
paramNames []string
}
type RouteTable struct {
routes *list.List
}
func (rt *RouteTable) Register(method HttpMethod, pattern *regexp.Regexp, paramNames []string, handler HandlerFunc, segments int, endsWildcard bool, middlewares ...Middleware) {
route := &RouteEntry{
method: method,
pattern: pattern,
handler: handler,
middlewares: middlewares,
paramNames: paramNames,
}
logs.Debug("map url %v to %v", pattern.String(), handler)
//TODO:路由的优先级
rt.routes.PushBack(route)
}
//http://stackoverflow.com/questions/30483652/how-to-get-capturing-group-functionality-in-golang-regular-expressions
// Match 匹配
func (rt *RouteTable) Match(method HttpMethod, url *url.URL) (*RouteData, bool) {
//url := ""
var route *RouteEntry
elem := rt.routes.Front()
for elem != nil {
route, _ = elem.Value.(*RouteEntry)
elem = elem.Next()
if route == nil || !method.In(route.method) {
continue
}
if route.pattern.MatchString(url.Path) {
// logs.Debug("%v in %v = %v", method, route.method, method.In(route.method))
// if !method.In(route.method) {
// logs.Debug("not ok")
// continue
// }
return &RouteData{
entry: route,
matchedUrl: url.Path,
}, true
}
}
return nil, false
}