1package chi
2
3// Radix tree implementation below is a based on the original work by
4// Armon Dadgar in https://github.com/armon/go-radix/blob/master/radix.go
5// (MIT licensed). It's been heavily modified for use as a HTTP routing tree.
6
7import (
8	"fmt"
9	"math"
10	"net/http"
11	"regexp"
12	"sort"
13	"strconv"
14	"strings"
15)
16
17type methodTyp int
18
19const (
20	mSTUB methodTyp = 1 << iota
21	mCONNECT
22	mDELETE
23	mGET
24	mHEAD
25	mOPTIONS
26	mPATCH
27	mPOST
28	mPUT
29	mTRACE
30)
31
32var mALL = mCONNECT | mDELETE | mGET | mHEAD |
33	mOPTIONS | mPATCH | mPOST | mPUT | mTRACE
34
35var methodMap = map[string]methodTyp{
36	http.MethodConnect: mCONNECT,
37	http.MethodDelete:  mDELETE,
38	http.MethodGet:     mGET,
39	http.MethodHead:    mHEAD,
40	http.MethodOptions: mOPTIONS,
41	http.MethodPatch:   mPATCH,
42	http.MethodPost:    mPOST,
43	http.MethodPut:     mPUT,
44	http.MethodTrace:   mTRACE,
45}
46
47// RegisterMethod adds support for custom HTTP method handlers, available
48// via Router#Method and Router#MethodFunc
49func RegisterMethod(method string) {
50	if method == "" {
51		return
52	}
53	method = strings.ToUpper(method)
54	if _, ok := methodMap[method]; ok {
55		return
56	}
57	n := len(methodMap)
58	if n > strconv.IntSize {
59		panic(fmt.Sprintf("chi: max number of methods reached (%d)", strconv.IntSize))
60	}
61	mt := methodTyp(math.Exp2(float64(n)))
62	methodMap[method] = mt
63	mALL |= mt
64}
65
66type nodeTyp uint8
67
68const (
69	ntStatic   nodeTyp = iota // /home
70	ntRegexp                  // /{id:[0-9]+}
71	ntParam                   // /{user}
72	ntCatchAll                // /api/v1/*
73)
74
75type node struct {
76	// node type: static, regexp, param, catchAll
77	typ nodeTyp
78
79	// first byte of the prefix
80	label byte
81
82	// first byte of the child prefix
83	tail byte
84
85	// prefix is the common prefix we ignore
86	prefix string
87
88	// regexp matcher for regexp nodes
89	rex *regexp.Regexp
90
91	// HTTP handler endpoints on the leaf node
92	endpoints endpoints
93
94	// subroutes on the leaf node
95	subroutes Routes
96
97	// child nodes should be stored in-order for iteration,
98	// in groups of the node type.
99	children [ntCatchAll + 1]nodes
100}
101
102// endpoints is a mapping of http method constants to handlers
103// for a given route.
104type endpoints map[methodTyp]*endpoint
105
106type endpoint struct {
107	// endpoint handler
108	handler http.Handler
109
110	// pattern is the routing pattern for handler nodes
111	pattern string
112
113	// parameter keys recorded on handler nodes
114	paramKeys []string
115}
116
117func (s endpoints) Value(method methodTyp) *endpoint {
118	mh, ok := s[method]
119	if !ok {
120		mh = &endpoint{}
121		s[method] = mh
122	}
123	return mh
124}
125
126func (n *node) InsertRoute(method methodTyp, pattern string, handler http.Handler) *node {
127	var parent *node
128	search := pattern
129
130	for {
131		// Handle key exhaustion
132		if len(search) == 0 {
133			// Insert or update the node's leaf handler
134			n.setEndpoint(method, handler, pattern)
135			return n
136		}
137
138		// We're going to be searching for a wild node next,
139		// in this case, we need to get the tail
140		var label = search[0]
141		var segTail byte
142		var segEndIdx int
143		var segTyp nodeTyp
144		var segRexpat string
145		if label == '{' || label == '*' {
146			segTyp, _, segRexpat, segTail, _, segEndIdx = patNextSegment(search)
147		}
148
149		var prefix string
150		if segTyp == ntRegexp {
151			prefix = segRexpat
152		}
153
154		// Look for the edge to attach to
155		parent = n
156		n = n.getEdge(segTyp, label, segTail, prefix)
157
158		// No edge, create one
159		if n == nil {
160			child := &node{label: label, tail: segTail, prefix: search}
161			hn := parent.addChild(child, search)
162			hn.setEndpoint(method, handler, pattern)
163
164			return hn
165		}
166
167		// Found an edge to match the pattern
168
169		if n.typ > ntStatic {
170			// We found a param node, trim the param from the search path and continue.
171			// This param/wild pattern segment would already be on the tree from a previous
172			// call to addChild when creating a new node.
173			search = search[segEndIdx:]
174			continue
175		}
176
177		// Static nodes fall below here.
178		// Determine longest prefix of the search key on match.
179		commonPrefix := longestPrefix(search, n.prefix)
180		if commonPrefix == len(n.prefix) {
181			// the common prefix is as long as the current node's prefix we're attempting to insert.
182			// keep the search going.
183			search = search[commonPrefix:]
184			continue
185		}
186
187		// Split the node
188		child := &node{
189			typ:    ntStatic,
190			prefix: search[:commonPrefix],
191		}
192		parent.replaceChild(search[0], segTail, child)
193
194		// Restore the existing node
195		n.label = n.prefix[commonPrefix]
196		n.prefix = n.prefix[commonPrefix:]
197		child.addChild(n, n.prefix)
198
199		// If the new key is a subset, set the method/handler on this node and finish.
200		search = search[commonPrefix:]
201		if len(search) == 0 {
202			child.setEndpoint(method, handler, pattern)
203			return child
204		}
205
206		// Create a new edge for the node
207		subchild := &node{
208			typ:    ntStatic,
209			label:  search[0],
210			prefix: search,
211		}
212		hn := child.addChild(subchild, search)
213		hn.setEndpoint(method, handler, pattern)
214		return hn
215	}
216}
217
218// addChild appends the new `child` node to the tree using the `pattern` as the trie key.
219// For a URL router like chi's, we split the static, param, regexp and wildcard segments
220// into different nodes. In addition, addChild will recursively call itself until every
221// pattern segment is added to the url pattern tree as individual nodes, depending on type.
222func (n *node) addChild(child *node, prefix string) *node {
223	search := prefix
224
225	// handler leaf node added to the tree is the child.
226	// this may be overridden later down the flow
227	hn := child
228
229	// Parse next segment
230	segTyp, _, segRexpat, segTail, segStartIdx, segEndIdx := patNextSegment(search)
231
232	// Add child depending on next up segment
233	switch segTyp {
234
235	case ntStatic:
236		// Search prefix is all static (that is, has no params in path)
237		// noop
238
239	default:
240		// Search prefix contains a param, regexp or wildcard
241
242		if segTyp == ntRegexp {
243			rex, err := regexp.Compile(segRexpat)
244			if err != nil {
245				panic(fmt.Sprintf("chi: invalid regexp pattern '%s' in route param", segRexpat))
246			}
247			child.prefix = segRexpat
248			child.rex = rex
249		}
250
251		if segStartIdx == 0 {
252			// Route starts with a param
253			child.typ = segTyp
254
255			if segTyp == ntCatchAll {
256				segStartIdx = -1
257			} else {
258				segStartIdx = segEndIdx
259			}
260			if segStartIdx < 0 {
261				segStartIdx = len(search)
262			}
263			child.tail = segTail // for params, we set the tail
264
265			if segStartIdx != len(search) {
266				// add static edge for the remaining part, split the end.
267				// its not possible to have adjacent param nodes, so its certainly
268				// going to be a static node next.
269
270				search = search[segStartIdx:] // advance search position
271
272				nn := &node{
273					typ:    ntStatic,
274					label:  search[0],
275					prefix: search,
276				}
277				hn = child.addChild(nn, search)
278			}
279
280		} else if segStartIdx > 0 {
281			// Route has some param
282
283			// starts with a static segment
284			child.typ = ntStatic
285			child.prefix = search[:segStartIdx]
286			child.rex = nil
287
288			// add the param edge node
289			search = search[segStartIdx:]
290
291			nn := &node{
292				typ:   segTyp,
293				label: search[0],
294				tail:  segTail,
295			}
296			hn = child.addChild(nn, search)
297
298		}
299	}
300
301	n.children[child.typ] = append(n.children[child.typ], child)
302	n.children[child.typ].Sort()
303	return hn
304}
305
306func (n *node) replaceChild(label, tail byte, child *node) {
307	for i := 0; i < len(n.children[child.typ]); i++ {
308		if n.children[child.typ][i].label == label && n.children[child.typ][i].tail == tail {
309			n.children[child.typ][i] = child
310			n.children[child.typ][i].label = label
311			n.children[child.typ][i].tail = tail
312			return
313		}
314	}
315	panic("chi: replacing missing child")
316}
317
318func (n *node) getEdge(ntyp nodeTyp, label, tail byte, prefix string) *node {
319	nds := n.children[ntyp]
320	for i := 0; i < len(nds); i++ {
321		if nds[i].label == label && nds[i].tail == tail {
322			if ntyp == ntRegexp && nds[i].prefix != prefix {
323				continue
324			}
325			return nds[i]
326		}
327	}
328	return nil
329}
330
331func (n *node) setEndpoint(method methodTyp, handler http.Handler, pattern string) {
332	// Set the handler for the method type on the node
333	if n.endpoints == nil {
334		n.endpoints = make(endpoints, 0)
335	}
336
337	paramKeys := patParamKeys(pattern)
338
339	if method&mSTUB == mSTUB {
340		n.endpoints.Value(mSTUB).handler = handler
341	}
342	if method&mALL == mALL {
343		h := n.endpoints.Value(mALL)
344		h.handler = handler
345		h.pattern = pattern
346		h.paramKeys = paramKeys
347		for _, m := range methodMap {
348			h := n.endpoints.Value(m)
349			h.handler = handler
350			h.pattern = pattern
351			h.paramKeys = paramKeys
352		}
353	} else {
354		h := n.endpoints.Value(method)
355		h.handler = handler
356		h.pattern = pattern
357		h.paramKeys = paramKeys
358	}
359}
360
361func (n *node) FindRoute(rctx *Context, method methodTyp, path string) (*node, endpoints, http.Handler) {
362	// Reset the context routing pattern and params
363	rctx.routePattern = ""
364	rctx.routeParams.Keys = rctx.routeParams.Keys[:0]
365	rctx.routeParams.Values = rctx.routeParams.Values[:0]
366
367	// Find the routing handlers for the path
368	rn := n.findRoute(rctx, method, path)
369	if rn == nil {
370		return nil, nil, nil
371	}
372
373	// Record the routing params in the request lifecycle
374	rctx.URLParams.Keys = append(rctx.URLParams.Keys, rctx.routeParams.Keys...)
375	rctx.URLParams.Values = append(rctx.URLParams.Values, rctx.routeParams.Values...)
376
377	// Record the routing pattern in the request lifecycle
378	if rn.endpoints[method].pattern != "" {
379		rctx.routePattern = rn.endpoints[method].pattern
380		rctx.RoutePatterns = append(rctx.RoutePatterns, rctx.routePattern)
381	}
382
383	return rn, rn.endpoints, rn.endpoints[method].handler
384}
385
386// Recursive edge traversal by checking all nodeTyp groups along the way.
387// It's like searching through a multi-dimensional radix trie.
388func (n *node) findRoute(rctx *Context, method methodTyp, path string) *node {
389	nn := n
390	search := path
391
392	for t, nds := range nn.children {
393		ntyp := nodeTyp(t)
394		if len(nds) == 0 {
395			continue
396		}
397
398		var xn *node
399		xsearch := search
400
401		var label byte
402		if search != "" {
403			label = search[0]
404		}
405
406		switch ntyp {
407		case ntStatic:
408			xn = nds.findEdge(label)
409			if xn == nil || !strings.HasPrefix(xsearch, xn.prefix) {
410				continue
411			}
412			xsearch = xsearch[len(xn.prefix):]
413
414		case ntParam, ntRegexp:
415			// short-circuit and return no matching route for empty param values
416			if xsearch == "" {
417				continue
418			}
419
420			// serially loop through each node grouped by the tail delimiter
421			for idx := 0; idx < len(nds); idx++ {
422				xn = nds[idx]
423
424				// label for param nodes is the delimiter byte
425				p := strings.IndexByte(xsearch, xn.tail)
426
427				if p < 0 {
428					if xn.tail == '/' {
429						p = len(xsearch)
430					} else {
431						continue
432					}
433				}
434
435				if ntyp == ntRegexp && xn.rex != nil {
436					if xn.rex.Match([]byte(xsearch[:p])) == false {
437						continue
438					}
439				} else if strings.IndexByte(xsearch[:p], '/') != -1 {
440					// avoid a match across path segments
441					continue
442				}
443
444				rctx.routeParams.Values = append(rctx.routeParams.Values, xsearch[:p])
445				xsearch = xsearch[p:]
446				break
447			}
448
449		default:
450			// catch-all nodes
451			rctx.routeParams.Values = append(rctx.routeParams.Values, search)
452			xn = nds[0]
453			xsearch = ""
454		}
455
456		if xn == nil {
457			continue
458		}
459
460		// did we find it yet?
461		if len(xsearch) == 0 {
462			if xn.isLeaf() {
463				h, _ := xn.endpoints[method]
464				if h != nil && h.handler != nil {
465					rctx.routeParams.Keys = append(rctx.routeParams.Keys, h.paramKeys...)
466					return xn
467				}
468
469				// flag that the routing context found a route, but not a corresponding
470				// supported method
471				rctx.methodNotAllowed = true
472			}
473		}
474
475		// recursively find the next node..
476		fin := xn.findRoute(rctx, method, xsearch)
477		if fin != nil {
478			return fin
479		}
480
481		// Did not find final handler, let's remove the param here if it was set
482		if xn.typ > ntStatic {
483			if len(rctx.routeParams.Values) > 0 {
484				rctx.routeParams.Values = rctx.routeParams.Values[:len(rctx.routeParams.Values)-1]
485			}
486		}
487
488	}
489
490	return nil
491}
492
493func (n *node) findEdge(ntyp nodeTyp, label byte) *node {
494	nds := n.children[ntyp]
495	num := len(nds)
496	idx := 0
497
498	switch ntyp {
499	case ntStatic, ntParam, ntRegexp:
500		i, j := 0, num-1
501		for i <= j {
502			idx = i + (j-i)/2
503			if label > nds[idx].label {
504				i = idx + 1
505			} else if label < nds[idx].label {
506				j = idx - 1
507			} else {
508				i = num // breaks cond
509			}
510		}
511		if nds[idx].label != label {
512			return nil
513		}
514		return nds[idx]
515
516	default: // catch all
517		return nds[idx]
518	}
519}
520
521func (n *node) isEmpty() bool {
522	for _, nds := range n.children {
523		if len(nds) > 0 {
524			return false
525		}
526	}
527	return true
528}
529
530func (n *node) isLeaf() bool {
531	return n.endpoints != nil
532}
533
534func (n *node) findPattern(pattern string) bool {
535	nn := n
536	for _, nds := range nn.children {
537		if len(nds) == 0 {
538			continue
539		}
540
541		n = nn.findEdge(nds[0].typ, pattern[0])
542		if n == nil {
543			continue
544		}
545
546		var idx int
547		var xpattern string
548
549		switch n.typ {
550		case ntStatic:
551			idx = longestPrefix(pattern, n.prefix)
552			if idx < len(n.prefix) {
553				continue
554			}
555
556		case ntParam, ntRegexp:
557			idx = strings.IndexByte(pattern, '}') + 1
558
559		case ntCatchAll:
560			idx = longestPrefix(pattern, "*")
561
562		default:
563			panic("chi: unknown node type")
564		}
565
566		xpattern = pattern[idx:]
567		if len(xpattern) == 0 {
568			return true
569		}
570
571		return n.findPattern(xpattern)
572	}
573	return false
574}
575
576func (n *node) routes() []Route {
577	rts := []Route{}
578
579	n.walk(func(eps endpoints, subroutes Routes) bool {
580		if eps[mSTUB] != nil && eps[mSTUB].handler != nil && subroutes == nil {
581			return false
582		}
583
584		// Group methodHandlers by unique patterns
585		pats := make(map[string]endpoints, 0)
586
587		for mt, h := range eps {
588			if h.pattern == "" {
589				continue
590			}
591			p, ok := pats[h.pattern]
592			if !ok {
593				p = endpoints{}
594				pats[h.pattern] = p
595			}
596			p[mt] = h
597		}
598
599		for p, mh := range pats {
600			hs := make(map[string]http.Handler, 0)
601			if mh[mALL] != nil && mh[mALL].handler != nil {
602				hs["*"] = mh[mALL].handler
603			}
604
605			for mt, h := range mh {
606				if h.handler == nil {
607					continue
608				}
609				m := methodTypString(mt)
610				if m == "" {
611					continue
612				}
613				hs[m] = h.handler
614			}
615
616			rt := Route{p, hs, subroutes}
617			rts = append(rts, rt)
618		}
619
620		return false
621	})
622
623	return rts
624}
625
626func (n *node) walk(fn func(eps endpoints, subroutes Routes) bool) bool {
627	// Visit the leaf values if any
628	if (n.endpoints != nil || n.subroutes != nil) && fn(n.endpoints, n.subroutes) {
629		return true
630	}
631
632	// Recurse on the children
633	for _, ns := range n.children {
634		for _, cn := range ns {
635			if cn.walk(fn) {
636				return true
637			}
638		}
639	}
640	return false
641}
642
643// patNextSegment returns the next segment details from a pattern:
644// node type, param key, regexp string, param tail byte, param starting index, param ending index
645func patNextSegment(pattern string) (nodeTyp, string, string, byte, int, int) {
646	ps := strings.Index(pattern, "{")
647	ws := strings.Index(pattern, "*")
648
649	if ps < 0 && ws < 0 {
650		return ntStatic, "", "", 0, 0, len(pattern) // we return the entire thing
651	}
652
653	// Sanity check
654	if ps >= 0 && ws >= 0 && ws < ps {
655		panic("chi: wildcard '*' must be the last pattern in a route, otherwise use a '{param}'")
656	}
657
658	var tail byte = '/' // Default endpoint tail to / byte
659
660	if ps >= 0 {
661		// Param/Regexp pattern is next
662		nt := ntParam
663
664		// Read to closing } taking into account opens and closes in curl count (cc)
665		cc := 0
666		pe := ps
667		for i, c := range pattern[ps:] {
668			if c == '{' {
669				cc++
670			} else if c == '}' {
671				cc--
672				if cc == 0 {
673					pe = ps + i
674					break
675				}
676			}
677		}
678		if pe == ps {
679			panic("chi: route param closing delimiter '}' is missing")
680		}
681
682		key := pattern[ps+1 : pe]
683		pe++ // set end to next position
684
685		if pe < len(pattern) {
686			tail = pattern[pe]
687		}
688
689		var rexpat string
690		if idx := strings.Index(key, ":"); idx >= 0 {
691			nt = ntRegexp
692			rexpat = key[idx+1:]
693			key = key[:idx]
694		}
695
696		if len(rexpat) > 0 {
697			if rexpat[0] != '^' {
698				rexpat = "^" + rexpat
699			}
700			if rexpat[len(rexpat)-1] != '$' {
701				rexpat = rexpat + "$"
702			}
703		}
704
705		return nt, key, rexpat, tail, ps, pe
706	}
707
708	// Wildcard pattern as finale
709	if ws < len(pattern)-1 {
710		panic("chi: wildcard '*' must be the last value in a route. trim trailing text or use a '{param}' instead")
711	}
712	return ntCatchAll, "*", "", 0, ws, len(pattern)
713}
714
715func patParamKeys(pattern string) []string {
716	pat := pattern
717	paramKeys := []string{}
718	for {
719		ptyp, paramKey, _, _, _, e := patNextSegment(pat)
720		if ptyp == ntStatic {
721			return paramKeys
722		}
723		for i := 0; i < len(paramKeys); i++ {
724			if paramKeys[i] == paramKey {
725				panic(fmt.Sprintf("chi: routing pattern '%s' contains duplicate param key, '%s'", pattern, paramKey))
726			}
727		}
728		paramKeys = append(paramKeys, paramKey)
729		pat = pat[e:]
730	}
731}
732
733// longestPrefix finds the length of the shared prefix
734// of two strings
735func longestPrefix(k1, k2 string) int {
736	max := len(k1)
737	if l := len(k2); l < max {
738		max = l
739	}
740	var i int
741	for i = 0; i < max; i++ {
742		if k1[i] != k2[i] {
743			break
744		}
745	}
746	return i
747}
748
749func methodTypString(method methodTyp) string {
750	for s, t := range methodMap {
751		if method == t {
752			return s
753		}
754	}
755	return ""
756}
757
758type nodes []*node
759
760// Sort the list of nodes by label
761func (ns nodes) Sort()              { sort.Sort(ns); ns.tailSort() }
762func (ns nodes) Len() int           { return len(ns) }
763func (ns nodes) Swap(i, j int)      { ns[i], ns[j] = ns[j], ns[i] }
764func (ns nodes) Less(i, j int) bool { return ns[i].label < ns[j].label }
765
766// tailSort pushes nodes with '/' as the tail to the end of the list for param nodes.
767// The list order determines the traversal order.
768func (ns nodes) tailSort() {
769	for i := len(ns) - 1; i >= 0; i-- {
770		if ns[i].typ > ntStatic && ns[i].tail == '/' {
771			ns.Swap(i, len(ns)-1)
772			return
773		}
774	}
775}
776
777func (ns nodes) findEdge(label byte) *node {
778	num := len(ns)
779	idx := 0
780	i, j := 0, num-1
781	for i <= j {
782		idx = i + (j-i)/2
783		if label > ns[idx].label {
784			i = idx + 1
785		} else if label < ns[idx].label {
786			j = idx - 1
787		} else {
788			i = num // breaks cond
789		}
790	}
791	if ns[idx].label != label {
792		return nil
793	}
794	return ns[idx]
795}
796
797// Route describes the details of a routing handler.
798type Route struct {
799	Pattern   string
800	Handlers  map[string]http.Handler
801	SubRoutes Routes
802}
803
804// WalkFunc is the type of the function called for each method and route visited by Walk.
805type WalkFunc func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error
806
807// Walk walks any router tree that implements Routes interface.
808func Walk(r Routes, walkFn WalkFunc) error {
809	return walk(r, walkFn, "")
810}
811
812func walk(r Routes, walkFn WalkFunc, parentRoute string, parentMw ...func(http.Handler) http.Handler) error {
813	for _, route := range r.Routes() {
814		mws := make([]func(http.Handler) http.Handler, len(parentMw))
815		copy(mws, parentMw)
816		mws = append(mws, r.Middlewares()...)
817
818		if route.SubRoutes != nil {
819			if err := walk(route.SubRoutes, walkFn, parentRoute+route.Pattern, mws...); err != nil {
820				return err
821			}
822			continue
823		}
824
825		for method, handler := range route.Handlers {
826			if method == "*" {
827				// Ignore a "catchAll" method, since we pass down all the specific methods for each route.
828				continue
829			}
830
831			fullRoute := parentRoute + route.Pattern
832
833			if chain, ok := handler.(*ChainHandler); ok {
834				if err := walkFn(method, fullRoute, chain.Endpoint, append(mws, chain.Middlewares...)...); err != nil {
835					return err
836				}
837			} else {
838				if err := walkFn(method, fullRoute, handler, mws...); err != nil {
839					return err
840				}
841			}
842		}
843	}
844
845	return nil
846}
847