-
-
Notifications
You must be signed in to change notification settings - Fork 366
/
route.go
56 lines (45 loc) · 1.07 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 app
import "regexp"
var (
routes router
)
// Route binds the requested path to the given UI node.
func Route(path string, node UI) {
routes.route(path, node)
}
// RouteWithRegexp binds the regular expression pattern to the given UI node.
// Patterns use the Go standard regexp format.
func RouteWithRegexp(pattern string, node UI) {
routes.routeWithRegexp(pattern, node)
}
type router struct {
routes map[string]UI
routesWithRegexp []regexpRoute
}
func (r *router) route(path string, node UI) {
if r.routes == nil {
r.routes = make(map[string]UI)
}
r.routes[path] = node
}
func (r *router) routeWithRegexp(pattern string, node UI) {
r.routesWithRegexp = append(r.routesWithRegexp, regexpRoute{
regexp: regexp.MustCompile(pattern),
node: node,
})
}
func (r *router) ui(path string) (UI, bool) {
if node, routed := r.routes[path]; routed {
return node, true
}
for _, r := range r.routesWithRegexp {
if r.regexp.MatchString(path) {
return r.node, true
}
}
return nil, false
}
type regexpRoute struct {
regexp *regexp.Regexp
node UI
}