/
route.go
74 lines (58 loc) · 1.31 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
package app
import (
"regexp"
"sync"
)
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) routed(path string) bool {
r.mu.RLock()
defer r.mu.RUnlock()
if _, routed := r.routes[path]; routed {
return true
}
for _, rwr := range r.routesWithRegexp {
if rwr.regexp.MatchString(path) {
return true
}
}
return false
}
func (r *router) createComponent(path string) (Composer, bool) {
r.mu.RLock()
defer r.mu.RUnlock()
if newComponent, routed := r.routes[path]; routed {
return newComponent(), true
}
for _, rwr := range r.routesWithRegexp {
if rwr.regexp.MatchString(path) {
return rwr.newComponent(), true
}
}
return nil, false
}
type regexpRoute struct {
regexp *regexp.Regexp
newComponent func() Composer
}