-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroutemap.go
70 lines (55 loc) · 1.26 KB
/
routemap.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
package main
import (
"fmt"
"sort"
"strings"
)
type RouteMap []RouteRule
func NewRouteMap(sc *ServerConfig) (RouteMap, error) {
var rm RouteMap
if sc == nil {
return rm, nil
}
routes := make([]string, 0, len(sc.Routes))
for r := range sc.Routes {
if !strings.HasPrefix(r, "/") {
return nil, fmt.Errorf("stiff.json: invalid route %q, missing leading slash", r)
}
routes = append(routes, r)
}
// sort in reverse so that the longer matches will go first
sort.Sort(sort.Reverse(sort.StringSlice(routes)))
for _, route := range routes {
rc := sc.Routes[route]
rule := RouteRule{
pattern: route,
matchDir: strings.HasSuffix(route, "/"),
config: NewRouteConfig(sc, &rc),
}
rm = append(rm, rule)
}
if _, found := sc.Routes["/"]; !found {
rm = append(rm, RouteRule{pattern: "/", matchDir: true, config: NewRouteConfig(sc, nil)})
}
return rm, nil
}
func (rm RouteMap) GetConfig(route string) RouteConfig {
for _, r := range rm {
if r.matches(route) {
return r.config
}
}
return defaultConfig
}
type RouteRule struct {
pattern string
matchDir bool
config RouteConfig
}
func (r RouteRule) matches(route string) bool {
if r.matchDir {
return strings.HasPrefix(route, r.pattern)
} else {
return route == r.pattern
}
}