-
-
Notifications
You must be signed in to change notification settings - Fork 356
/
route.go
99 lines (80 loc) · 2.23 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
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
package app
import (
"reflect"
"regexp"
"sync"
)
var (
routes = makeRouter()
)
// Route set the type of component to be mounted when a page is navigated to the
// given path.
func Route(path string, c Composer) {
RouteFunc(path, newZeroComponentFunc(c))
}
// RouteWithRegexp set the type of component to be mounted when a page is
// navigated to a path that matches the given pattern.
func RouteWithRegexp(pattern string, c Composer) {
RouteWithRegexpFunc(pattern, newZeroComponentFunc(c))
}
// RouteFunc set a function that creates the component to be mounted when a page
// is navigated to the given path.
func RouteFunc(path string, newComponent func() Composer) {
routes.route(path, newComponent)
}
// RouteWithRegexpFunc set a function that creates the component to be mounted
// when a page is navigated to a path that matches the given pattern.
func RouteWithRegexpFunc(pattern string, newComponent func() Composer) {
routes.routeWithRegexp(pattern, newComponent)
}
func newZeroComponentFunc(c Composer) func() Composer {
componentType := reflect.TypeOf(c)
return func() Composer {
return reflect.New(componentType.Elem()).Interface().(Composer)
}
}
type router struct {
mu sync.RWMutex
routes map[string]func() Composer
routesWithRegexp []regexpRoute
}
func makeRouter() router {
return router{
routes: make(map[string]func() Composer),
}
}
func (r *router) route(path string, newComponent func() Composer) {
r.mu.Lock()
defer r.mu.Unlock()
r.routes[path] = newComponent
}
func (r *router) routeWithRegexp(pattern string, newComponent func() Composer) {
r.mu.Lock()
defer r.mu.Unlock()
r.routesWithRegexp = append(r.routesWithRegexp, regexpRoute{
regexp: regexp.MustCompile(pattern),
newComponent: newComponent,
})
}
func (r *router) createComponent(path string) (Composer, bool) {
r.mu.RLock()
defer r.mu.RUnlock()
newComponent, isRouted := r.routes[path]
if !isRouted {
for _, rwr := range r.routesWithRegexp {
if rwr.regexp.MatchString(path) {
newComponent = rwr.newComponent
isRouted = true
break
}
}
}
if !isRouted {
return nil, false
}
return newComponent(), true
}
type regexpRoute struct {
regexp *regexp.Regexp
newComponent func() Composer
}