-
Notifications
You must be signed in to change notification settings - Fork 1
/
dispatch.go
215 lines (192 loc) · 5.87 KB
/
dispatch.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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
package dispatch
import (
"errors"
"fmt"
"net/http"
"strings"
)
type Handler func(http.ResponseWriter, *http.Request, map[string]string)
type Dispatcher struct {
root *dispatchNode
}
type dispatchNode struct {
LiteralNexts map[string]*dispatchNode
ArgumentNexts map[string]*dispatchNode
StarNext *dispatchNode
// The handler and pattern for this node if one exists.
Handler Handler
Pattern string
}
func (n *dispatchNode) init() *dispatchNode {
n.LiteralNexts = make(map[string]*dispatchNode)
n.ArgumentNexts = make(map[string]*dispatchNode)
n.StarNext = nil
return n
}
// Adds the specified handler with the specified pattern.
//
// The pattern format is described below.
//
// By default, the pattern is an exact-prefix match. Query parameters never
// matter for the purpose of dispatch.
// PATTERN : /foo
// MATCHES : /foo, /foo?arg=1
// MISMATCHES: /foobar, /foo/bar
//
// PATTERN : /foo/bar
// MATCHES : /foo/bar, /foo/bar?arg=1
// MISMATCHES: /foobar, /foo/bar/baz
//
// "/*" Can be used to construct a non-exact-match prefix. Note that paths like
// "/foo*" or "/foo/*/bar" are invalid. "/*" must terminate the pattern.
// PATTERN : /foo/*
// MATCHES : /foo/bar, /foo/bar/baz
// MISMATCHES: /foo, /foobar
//
// "/<key>" Can be used as a wildcard for a path segment. The content of that path
// segment is forwarded to the dispatcher in the map.
// PATTERN : /foo/<a>
// MATCHES : /foo/1 (a:1), /foo/2 (a:2)
// MISMATCHES: /foo, /foo/bar/baz, /foobar
//
// PATTERN : /foo/<a>/<b>
// MATCHES : /foo/1/2 (a:1,b:2)
// MISMATCHES: /foo, /foo/1, /foo/1/2/3
func (dispatcher *Dispatcher) Add(pattern string, handler Handler) error {
if dispatcher.root == nil {
// Ensure root node is initialized.
dispatcher.root = new(dispatchNode).init()
}
// Ensure pattern starts with "/"
if !strings.HasPrefix(pattern, "/") {
return errors.New(fmt.Sprintf("pattern must start with '/': %v", pattern))
}
// Split pattern into parts
patternParts := strings.Split(pattern, "/")
var node *dispatchNode = nil
for i, patternPart := range patternParts {
switch {
case i == 0:
node = dispatcher.root
case len(patternPart) == 0:
if i == len(patternParts)-1 {
// Ignore trailing '/'
break
} else {
return errors.New(fmt.Sprintf(
"pattern cannot have two consecutive '/': %v", pattern))
}
case patternPart == "*":
if i != len(patternParts)-1 {
return errors.New(fmt.Sprintf(
"pattern containing '*' must end with '*': %v", pattern))
}
if node.StarNext == nil {
node.StarNext = new(dispatchNode).init()
}
node = node.StarNext
case strings.HasPrefix(patternPart, "<"):
if !strings.HasSuffix(patternPart, ">") {
return errors.New(fmt.Sprintf(
"pattern has unterminated '<' bracket: %v", pattern))
} else {
// TODO: This implementation allows conflicting patterns if the argument
// name differs. Ex: Only one of '/<a>' and '/<b>' will be selected.
argument := patternPart[1 : len(patternPart)-1]
nextNode, exists := node.ArgumentNexts[argument]
if !exists {
nextNode = new(dispatchNode).init()
node.ArgumentNexts[argument] = nextNode
}
node = nextNode
}
default:
literal := patternPart
nextNode, exists := node.LiteralNexts[literal]
if !exists {
nextNode = new(dispatchNode).init()
node.LiteralNexts[literal] = nextNode
}
node = nextNode
}
}
// If we got here then the pattern was valid and fully consumed.
if node.Handler != nil {
return errors.New(fmt.Sprintf(
"pattern conflicts with existing pattern '%v': %v",
node.Pattern, pattern))
}
node.Handler = handler
node.Pattern = pattern
return nil
}
func recSelect(
pathIndex int,
pathParts []string,
node *dispatchNode,
argAccum *map[string]string) Handler {
// We do a DFS to match the most specific patterns first.
// Base case: consumed the entire path, if there is a match return it.
if pathIndex == len(pathParts) {
return node.Handler
}
part := pathParts[pathIndex]
// Base case: consumed the entire path, path has a trailing '/'. If there is
// a match return it.
if pathIndex == len(pathParts)-1 && part == "" {
return node.Handler
}
// Recursive case: check for literal matches. Only return if there is a match.
// Otherwise check next recursive case.
nextNode, exists := node.LiteralNexts[part]
if exists {
handler := recSelect(pathIndex+1, pathParts, nextNode, argAccum)
if handler != nil {
return handler
}
}
// Recursive case: check for argument segment matches. Only return if there is
// a match. Otherwise check next recursive case.
for arg, nextNode := range node.ArgumentNexts {
handler := recSelect(pathIndex+1, pathParts, nextNode, argAccum)
if handler != nil {
(*argAccum)[arg] = part
return handler
}
}
// Recursive case: check for star matches.
if node.StarNext != nil {
return node.StarNext.Handler
}
// Recursive case: No matchers, return early.
return nil
}
func (dispatcher *Dispatcher) Select(
path string) (handler Handler, args map[string]string, err error) {
handler, args, err = nil, make(map[string]string), nil
// strip ?... and #...
path = strings.Split(path, "?")[0]
path = strings.Split(path, "#")[0]
if !strings.HasPrefix(path, "/") {
err = errors.New(fmt.Sprintf("input path is not absolute: %v", path))
return
}
pathParts := strings.Split(path, "/")
handler = recSelect(1, pathParts, dispatcher.root, &args)
return
}
// Use http.HandleFunc("/", dispatcher.RootHandler) to use this dispatcher for
// dispatch in an application.
func (dispatcher *Dispatcher) RootHandler(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
handler, args, err := dispatcher.Select(path)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if handler == nil {
http.Error(w, fmt.Sprintf("HTTP 404 Not Found: %v", path), http.StatusNotFound)
return
}
handler(w, r, args)
}