Debian Codegraph @

rest/trie/impl.go

raw
1 // Special Trie implementation for HTTP routing.
2 //
3 // This Trie implementation is designed to support strings that includes
4 // :param and *splat parameters. Strings that are commonly used to represent
5 // the Path in HTTP routing. This implementation also maintain for each Path
6 // a map of HTTP Methods associated with the Route.
7 //
8 // You probably don't need to use this package directly.
9 //
10 package trie
11
12 import (
13 "errors"
14 "fmt"
15 )
16
17 func splitParam(remaining string) (string, string) {
18 i := 0
19 for len(remaining) > i && remaining[i] != '/' && remaining[i] != '.' {
20 i++
21 }
22 return remaining[:i], remaining[i:]
23 }
24
25 func splitRelaxed(remaining string) (string, string) {
26 i := 0
27 for len(remaining) > i && remaining[i] != '/' {
28 i++
29 }
30 return remaining[:i], remaining[i:]
31 }
32
33 type node struct {
34 HttpMethodToRoute map[string]interface{}
35
36 Children map[string]*node
37 ChildrenKeyLen int
38
39 ParamChild *node
40 ParamName string
41
42 RelaxedChild *node
43 RelaxedName string
44
45 SplatChild *node
46 SplatName string
47 }
48
49 func (n *node) addRoute(httpMethod, pathExp string, route interface{}, usedParams []string) error {
50
51 if len(pathExp) == 0 {
52 // end of the path, leaf node, update the map
53 if n.HttpMethodToRoute == nil {
54 n.HttpMethodToRoute = map[string]interface{}{
55 httpMethod: route,
56 }
57 return nil
58 } else {
59 if n.HttpMethodToRoute[httpMethod] != nil {
60 return errors.New("node.Route already set, duplicated path and method")
61 }
62 n.HttpMethodToRoute[httpMethod] = route
63 return nil
64 }
65 }
66
67 token := pathExp[0:1]
68 remaining := pathExp[1:]
69 var nextNode *node
70
71 if token[0] == ':' {
72 // :param case
73 var name string
74 name, remaining = splitParam(remaining)
75
76 // Check param name is unique
77 for _, e := range usedParams {
78 if e == name {
79 return errors.New(
80 fmt.Sprintf("A route can't have two placeholders with the same name: %s", name),
81 )
82 }
83 }
84 usedParams = append(usedParams, name)
85
86 if n.ParamChild == nil {
87 n.ParamChild = &node{}
88 n.ParamName = name
89 } else {
90 if n.ParamName != name {
91 return errors.New(
92 fmt.Sprintf(
93 "Routes sharing a common placeholder MUST name it consistently: %s != %s",
94 n.ParamName,
95 name,
96 ),
97 )
98 }
99 }
100 nextNode = n.ParamChild
101 } else if token[0] == '#' {
102 // #param case
103 var name string
104 name, remaining = splitRelaxed(remaining)
105
106 // Check param name is unique
107 for _, e := range usedParams {
108 if e == name {
109 return errors.New(
110 fmt.Sprintf("A route can't have two placeholders with the same name: %s", name),
111 )
112 }
113 }
114 usedParams = append(usedParams, name)
115
116 if n.RelaxedChild == nil {
117 n.RelaxedChild = &node{}
118 n.RelaxedName = name
119 } else {
120 if n.RelaxedName != name {
121 return errors.New(
122 fmt.Sprintf(
123 "Routes sharing a common placeholder MUST name it consistently: %s != %s",
124 n.RelaxedName,
125 name,
126 ),
127 )
128 }
129 }
130 nextNode = n.RelaxedChild
131 } else if token[0] == '*' {
132 // *splat case
133 name := remaining
134 remaining = ""
135
136 // Check param name is unique
137 for _, e := range usedParams {
138 if e == name {
139 return errors.New(
140 fmt.Sprintf("A route can't have two placeholders with the same name: %s", name),
141 )
142 }
143 }
144
145 if n.SplatChild == nil {
146 n.SplatChild = &node{}
147 n.SplatName = name
148 }
149 nextNode = n.SplatChild
150 } else {
151 // general case
152 if n.Children == nil {
153 n.Children = map[string]*node{}
154 n.ChildrenKeyLen = 1
155 }
156 if n.Children[token] == nil {
157 n.Children[token] = &node{}
158 }
159 nextNode = n.Children[token]
160 }
161
162 return nextNode.addRoute(httpMethod, remaining, route, usedParams)
163 }
164
165 func (n *node) compress() {
166 // *splat branch
167 if n.SplatChild != nil {
168 n.SplatChild.compress()
169 }
170 // :param branch
171 if n.ParamChild != nil {
172 n.ParamChild.compress()
173 }
174 // #param branch
175 if n.RelaxedChild != nil {
176 n.RelaxedChild.compress()
177 }
178 // main branch
179 if len(n.Children) == 0 {
180 return
181 }
182 // compressable ?
183 canCompress := true
184 for _, node := range n.Children {
185 if node.HttpMethodToRoute != nil || node.SplatChild != nil || node.ParamChild != nil || node.RelaxedChild != nil {
186 canCompress = false
187 }
188 }
189 // compress
190 if canCompress {
191 merged := map[string]*node{}
192 for key, node := range n.Children {
193 for gdKey, gdNode := range node.Children {
194 mergedKey := key + gdKey
195 merged[mergedKey] = gdNode
196 }
197 }
198 n.Children = merged
199 n.ChildrenKeyLen++
200 n.compress()
201 // continue
202 } else {
203 for _, node := range n.Children {
204 node.compress()
205 }
206 }
207 }
208
209 func printFPadding(padding int, format string, a ...interface{}) {
210 for i := 0; i < padding; i++ {
211 fmt.Print(" ")
212 }
213 fmt.Printf(format, a...)
214 }
215
216 // Private function for now
217 func (n *node) printDebug(level int) {
218 level++
219 // *splat branch
220 if n.SplatChild != nil {
221 printFPadding(level, "*splat\n")
222 n.SplatChild.printDebug(level)
223 }
224 // :param branch
225 if n.ParamChild != nil {
226 printFPadding(level, ":param\n")
227 n.ParamChild.printDebug(level)
228 }
229 // #param branch
230 if n.RelaxedChild != nil {
231 printFPadding(level, "#relaxed\n")
232 n.RelaxedChild.printDebug(level)
233 }
234 // main branch
235 for key, node := range n.Children {
236 printFPadding(level, "\"%s\"\n", key)
237 node.printDebug(level)
238 }
239 }
240
241 // utility for the node.findRoutes recursive method
242
243 type paramMatch struct {
244 name string
245 value string
246 }
247
248 type findContext struct {
249 paramStack []paramMatch
250 matchFunc func(httpMethod, path string, node *node)
251 }
252
253 func newFindContext() *findContext {
254 return &findContext{
255 paramStack: []paramMatch{},
256 }
257 }
258
259 func (fc *findContext) pushParams(name, value string) {
260 fc.paramStack = append(
261 fc.paramStack,
262 paramMatch{name, value},
263 )
264 }
265
266 func (fc *findContext) popParams() {
267 fc.paramStack = fc.paramStack[:len(fc.paramStack)-1]
268 }
269
270 func (fc *findContext) paramsAsMap() map[string]string {
271 r := map[string]string{}
272 for _, param := range fc.paramStack {
273 if r[param.name] != "" {
274 // this is checked at addRoute time, and should never happen.
275 panic(fmt.Sprintf(
276 "placeholder %s already found, placeholder names should be unique per route",
277 param.name,
278 ))
279 }
280 r[param.name] = param.value
281 }
282 return r
283 }
284
285 type Match struct {
286 // Same Route as in AddRoute
287 Route interface{}
288 // map of params matched for this result
289 Params map[string]string
290 }
291
292 func (n *node) find(httpMethod, path string, context *findContext) {
293
294 if n.HttpMethodToRoute != nil && path == "" {
295 context.matchFunc(httpMethod, path, n)
296 }
297
298 if len(path) == 0 {
299 return
300 }
301
302 // *splat branch
303 if n.SplatChild != nil {
304 context.pushParams(n.SplatName, path)
305 n.SplatChild.find(httpMethod, "", context)
306 context.popParams()
307 }
308
309 // :param branch
310 if n.ParamChild != nil {
311 value, remaining := splitParam(path)
312 context.pushParams(n.ParamName, value)
313 n.ParamChild.find(httpMethod, remaining, context)
314 context.popParams()
315 }
316
317 // #param branch
318 if n.RelaxedChild != nil {
319 value, remaining := splitRelaxed(path)
320 context.pushParams(n.RelaxedName, value)
321 n.RelaxedChild.find(httpMethod, remaining, context)
322 context.popParams()
323 }
324
325 // main branch
326 length := n.ChildrenKeyLen
327 if len(path) < length {
328 return
329 }
330 token := path[0:length]
331 remaining := path[length:]
332 if n.Children[token] != nil {
333 n.Children[token].find(httpMethod, remaining, context)
334 }
335 }
336
337 type Trie struct {
338 root *node
339 }
340
341 // Instanciate a Trie with an empty node as the root.
342 func New() *Trie {
343 return &Trie{
344 root: &node{},
345 }
346 }
347
348 // Insert the route in the Trie following or creating the nodes corresponding to the path.
349 func (t *Trie) AddRoute(httpMethod, pathExp string, route interface{}) error {
350 return t.root.addRoute(httpMethod, pathExp, route, []string{})
351 }
352
353 // Reduce the size of the tree, must be done after the last AddRoute.
354 func (t *Trie) Compress() {
355 t.root.compress()
356 }
357
358 // Private function for now.
359 func (t *Trie) printDebug() {
360 fmt.Print("<trie>\n")
361 t.root.printDebug(0)
362 fmt.Print("</trie>\n")
363 }
364
365 // Given a path and an http method, return all the matching routes.
366 func (t *Trie) FindRoutes(httpMethod, path string) []*Match {
367 context := newFindContext()
368 matches := []*Match{}
369 context.matchFunc = func(httpMethod, path string, node *node) {
370 if node.HttpMethodToRoute[httpMethod] != nil {
371 // path and method match, found a route !
372 matches = append(
373 matches,
374 &Match{
375 Route: node.HttpMethodToRoute[httpMethod],
376 Params: context.paramsAsMap(),
377 },
378 )
379 }
380 }
381 t.root.find(httpMethod, path, context)
382 return matches
383 }
384
385 // Same as FindRoutes, but return in addition a boolean indicating if the path was matched.
386 // Useful to return 405
387 func (t *Trie) FindRoutesAndPathMatched(httpMethod, path string) ([]*Match, bool) {
388 context := newFindContext()
389 pathMatched := false
390 matches := []*Match{}
391 context.matchFunc = func(httpMethod, path string, node *node) {
392 pathMatched = true
393 if node.HttpMethodToRoute[httpMethod] != nil {
394 // path and method match, found a route !
395 matches = append(
396 matches,
397 &Match{
398 Route: node.HttpMethodToRoute[httpMethod],
399 Params: context.paramsAsMap(),
400 },
401 )
402 }
403 }
404 t.root.find(httpMethod, path, context)
405 return matches, pathMatched
406 }
407
408 // Given a path, and whatever the http method, return all the matching routes.
409 func (t *Trie) FindRoutesForPath(path string) []*Match {
410 context := newFindContext()
411 matches := []*Match{}
412 context.matchFunc = func(httpMethod, path string, node *node) {
413 params := context.paramsAsMap()
414 for _, route := range node.HttpMethodToRoute {
415 matches = append(
416 matches,
417 &Match{
418 Route: route,
419 Params: params,
420 },
421 )
422 }
423 }
424 t.root.find("", path, context)
425 return matches
426 }