forked from vulcand/vulcan
/
exproute.go
135 lines (112 loc) · 2.52 KB
/
exproute.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
/*
Expression based request router, supports functions and combinations of functions in form
<What to match><Matching verb> and || and && operators.
*/
package exproute
import (
"fmt"
"sort"
"sync"
"github.com/FoxComm/vulcan/location"
"github.com/FoxComm/vulcan/request"
)
type ExpRouter struct {
mutex *sync.RWMutex
matchers []matcher
routes map[string]location.Location
}
func NewExpRouter() *ExpRouter {
return &ExpRouter{
mutex: &sync.RWMutex{},
routes: make(map[string]location.Location),
}
}
func (e *ExpRouter) GetLocationByExpression(expr string) location.Location {
e.mutex.RLock()
defer e.mutex.RUnlock()
return e.routes[expr]
}
func (e *ExpRouter) AddLocation(expr string, l location.Location) error {
e.mutex.Lock()
defer e.mutex.Unlock()
if _, ok := e.routes[expr]; ok {
return fmt.Errorf("Expression '%s' already exists", expr)
}
if _, err := parseExpression(expr, l); err != nil {
return err
}
e.routes[expr] = l
if err := e.compile(); err != nil {
delete(e.routes, expr)
return err
}
return nil
}
func (e *ExpRouter) compile() error {
var exprs = []string{}
for expr, _ := range e.routes {
exprs = append(exprs, expr)
}
sort.Sort(sort.Reverse(sort.StringSlice(exprs)))
matchers := []matcher{}
i := 0
for _, expr := range exprs {
location := e.routes[expr]
matcher, err := parseExpression(expr, location)
if err != nil {
return err
}
// Merge the previous and new matcher if that's possible
if i > 0 && matchers[i-1].canMerge(matcher) {
m, err := matchers[i-1].merge(matcher)
if err != nil {
return err
}
matchers[i-1] = m
} else {
matchers = append(matchers, matcher)
i += 1
}
}
e.matchers = matchers
return nil
}
func (e *ExpRouter) RemoveLocationByExpression(expr string) error {
e.mutex.Lock()
defer e.mutex.Unlock()
delete(e.routes, expr)
return e.compile()
}
func (e *ExpRouter) RemoveLocationById(id string) error {
e.mutex.Lock()
defer e.mutex.Unlock()
for expr, l := range e.routes {
if l.GetId() == id {
delete(e.routes, expr)
}
}
return e.compile()
}
func (e *ExpRouter) GetLocationById(id string) location.Location {
e.mutex.RLock()
defer e.mutex.RUnlock()
for _, l := range e.routes {
if l.GetId() == id {
return l
}
}
return nil
}
func (e *ExpRouter) Route(req request.Request) (location.Location, error) {
e.mutex.RLock()
defer e.mutex.RUnlock()
if len(e.matchers) == 0 {
return nil, nil
}
for _, m := range e.matchers {
if l := m.match(req); l != nil {
return l, nil
}
}
return nil, nil
}