Skip to content
Myr

tree.go

This file

Path

tree.go

957 lines · 24.3 KiB · Go

Last changed by

fix(tree): grow skippedNodes when pooled capacity is stale (#4852)HazyLabbefore adoptionea9fab9

History of this file

Take it

1// Copyright 2013 Julien Schmidt. All rights reserved.2// Use of this source code is governed by a BSD-style license that can be found3// at https://github.com/julienschmidt/httprouter/blob/master/LICENSE45package gin67import (8	"net/url"9	"strings"10	"unicode"11	"unicode/utf8"1213	"github.com/gin-gonic/gin/internal/bytesconv"14)1516// Param is a single URL parameter, consisting of a key and a value.17type Param struct {18	Key   string19	Value string20}2122// Params is a Param-slice, as returned by the router.23// The slice is ordered, the first URL parameter is also the first slice value.24// It is therefore safe to read values by the index.25type Params []Param2627// Get returns the value of the first Param which key matches the given name and a boolean true.28// If no matching Param is found, an empty string is returned and a boolean false .29func (ps Params) Get(name string) (string, bool) {30	for _, entry := range ps {31		if entry.Key == name {32			return entry.Value, true33		}34	}35	return "", false36}3738// ByName returns the value of the first Param which key matches the given name.39// If no matching Param is found, an empty string is returned.40func (ps Params) ByName(name string) (va string) {41	va, _ = ps.Get(name)42	return43}4445type methodTree struct {46	method string47	root   *node48}4950type methodTrees []methodTree5152func (trees methodTrees) get(method string) *node {53	for _, tree := range trees {54		if tree.method == method {55			return tree.root56		}57	}58	return nil59}6061func longestCommonPrefix(a, b string) int {62	i := 063	max_ := min(len(a), len(b))64	for i < max_ && a[i] == b[i] {65		i++66	}67	return i68}6970// addChild will add a child node, keeping wildcardChild at the end71func (n *node) addChild(child *node) {72	if n.wildChild && len(n.children) > 0 {73		wildcardChild := n.children[len(n.children)-1]74		n.children = append(n.children[:len(n.children)-1], child, wildcardChild)75	} else {76		n.children = append(n.children, child)77	}78}7980func countParams(path string) uint16 {81	colons := strings.Count(path, ":")82	stars := strings.Count(path, "*")83	return safeUint16(colons + stars)84}8586func countSections(path string) uint16 {87	return safeUint16(strings.Count(path, "/"))88}8990type nodeType uint89192const (93	static nodeType = iota94	root95	param96	catchAll97)9899type node struct {100	path      string101	indices   string102	wildChild bool103	nType     nodeType104	priority  uint32105	children  []*node // child nodes, at most 1 :param style node at the end of the array106	handlers  HandlersChain107	fullPath  string108}109110// incrementChildPrio increments the priority of the given child and reorders it if necessary.111func (n *node) incrementChildPrio(pos int) int {112	cs := n.children113	cs[pos].priority++114	prio := cs[pos].priority115116	// Adjust position (move to front)117	newPos := pos118	for ; newPos > 0 && cs[newPos-1].priority < prio; newPos-- {119		// Swap node positions120		cs[newPos-1], cs[newPos] = cs[newPos], cs[newPos-1]121	}122123	// Build new index char string124	if newPos != pos {125		n.indices = n.indices[:newPos] + // Unchanged prefix, might be empty126			n.indices[pos:pos+1] + // The index char we move127			n.indices[newPos:pos] + n.indices[pos+1:] // Rest without char at 'pos'128	}129130	return newPos131}132133// addRoute adds a node with the given handle to the path.134// Not concurrency-safe!135func (n *node) addRoute(path string, handlers HandlersChain) {136	fullPath := path137	n.priority++138139	// Empty tree140	if len(n.path) == 0 && len(n.children) == 0 {141		n.insertChild(path, fullPath, handlers)142		n.nType = root143		return144	}145146	parentFullPathIndex := 0147148walk:149	for {150		// Find the longest common prefix.151		// This also implies that the common prefix contains no ':' or '*'152		// since the existing key can't contain those chars.153		i := longestCommonPrefix(path, n.path)154155		// Split edge156		if i < len(n.path) {157			child := node{158				path:      n.path[i:],159				wildChild: n.wildChild,160				nType:     static,161				indices:   n.indices,162				children:  n.children,163				handlers:  n.handlers,164				priority:  n.priority - 1,165				fullPath:  n.fullPath,166			}167168			n.children = []*node{&child}169			// []byte for proper unicode char conversion, see #65170			n.indices = bytesconv.BytesToString([]byte{n.path[i]})171			n.path = path[:i]172			n.handlers = nil173			n.wildChild = false174			n.fullPath = fullPath[:parentFullPathIndex+i]175		}176177		// Make new node a child of this node178		if i < len(path) {179			path = path[i:]180			c := path[0]181182			// '/' after param183			if n.nType == param && c == '/' && len(n.children) == 1 {184				parentFullPathIndex += len(n.path)185				n = n.children[0]186				n.priority++187				continue walk188			}189190			// Check if a child with the next path byte exists191			for i, max_ := 0, len(n.indices); i < max_; i++ {192				if c == n.indices[i] {193					parentFullPathIndex += len(n.path)194					i = n.incrementChildPrio(i)195					n = n.children[i]196					continue walk197				}198			}199200			// Otherwise insert it201			if c != ':' && c != '*' && n.nType != catchAll {202				// []byte for proper unicode char conversion, see #65203				n.indices += bytesconv.BytesToString([]byte{c})204				child := &node{205					fullPath: fullPath,206				}207				n.addChild(child)208				n.incrementChildPrio(len(n.indices) - 1)209				n = child210			} else if n.wildChild {211				// inserting a wildcard node, need to check if it conflicts with the existing wildcard212				n = n.children[len(n.children)-1]213				n.priority++214215				// Check if the wildcard matches216				if len(path) >= len(n.path) && n.path == path[:len(n.path)] &&217					// Adding a child to a catchAll is not possible218					n.nType != catchAll &&219					// Check for longer wildcard, e.g. :name and :names220					(len(n.path) >= len(path) || path[len(n.path)] == '/') {221					continue walk222				}223224				// Wildcard conflict225				pathSeg := path226				if n.nType != catchAll {227					pathSeg, _, _ = strings.Cut(pathSeg, "/")228				}229				prefix := fullPath[:strings.Index(fullPath, pathSeg)] + n.path230				panic("'" + pathSeg +231					"' in new path '" + fullPath +232					"' conflicts with existing wildcard '" + n.path +233					"' in existing prefix '" + prefix +234					"'")235			}236237			n.insertChild(path, fullPath, handlers)238			return239		}240241		// Otherwise add handle to current node242		if n.handlers != nil {243			panic("handlers are already registered for path '" + fullPath + "'")244		}245		n.handlers = handlers246		n.fullPath = fullPath247		return248	}249}250251// Search for a wildcard segment and check the name for invalid characters.252// Returns -1 as index, if no wildcard was found.253func findWildcard(path string) (wildcard string, i int, valid bool) {254	// Find start255	escapeColon := false256	for start, c := range []byte(path) {257		if escapeColon {258			escapeColon = false259			if c == ':' {260				continue261			}262			panic("invalid escape string in path '" + path + "'")263		}264		if c == '\\' {265			escapeColon = true266			continue267		}268		// A wildcard starts with ':' (param) or '*' (catch-all)269		if c != ':' && c != '*' {270			continue271		}272273		// Find end and check for invalid characters274		valid = true275		for end, c := range []byte(path[start+1:]) {276			switch c {277			case '/':278				return path[start : start+1+end], start, valid279			case ':', '*':280				valid = false281			}282		}283		return path[start:], start, valid284	}285	return "", -1, false286}287288func (n *node) insertChild(path string, fullPath string, handlers HandlersChain) {289	for {290		// Find prefix until first wildcard291		wildcard, i, valid := findWildcard(path)292		if i < 0 { // No wildcard found293			break294		}295296		// The wildcard name must only contain one ':' or '*' character297		if !valid {298			panic("only one wildcard per path segment is allowed, has: '" +299				wildcard + "' in path '" + fullPath + "'")300		}301302		// check if the wildcard has a name303		if len(wildcard) < 2 {304			panic("wildcards must be named with a non-empty name in path '" + fullPath + "'")305		}306307		if wildcard[0] == ':' { // param308			if i > 0 {309				// Insert prefix before the current wildcard310				n.path = path[:i]311				path = path[i:]312			}313314			child := &node{315				nType:    param,316				path:     wildcard,317				fullPath: fullPath,318			}319			n.addChild(child)320			n.wildChild = true321			n = child322			n.priority++323324			// if the path doesn't end with the wildcard, then there325			// will be another subpath starting with '/'326			if len(wildcard) < len(path) {327				path = path[len(wildcard):]328329				child := &node{330					priority: 1,331					fullPath: fullPath,332				}333				n.addChild(child)334				n = child335				continue336			}337338			// Otherwise we're done. Insert the handle in the new leaf339			n.handlers = handlers340			return341		}342343		// catchAll344		if i+len(wildcard) != len(path) {345			panic("catch-all routes are only allowed at the end of the path in path '" + fullPath + "'")346		}347348		if len(n.path) > 0 && n.path[len(n.path)-1] == '/' {349			pathSeg := ""350			if len(n.children) != 0 {351				pathSeg, _, _ = strings.Cut(n.children[0].path, "/")352			}353			panic("catch-all wildcard '" + path +354				"' in new path '" + fullPath +355				"' conflicts with existing path segment '" + pathSeg +356				"' in existing prefix '" + n.path + pathSeg +357				"'")358		}359360		// currently fixed width 1 for '/'361		i--362		if i < 0 || path[i] != '/' {363			panic("no / before catch-all in path '" + fullPath + "'")364		}365366		n.path = path[:i]367368		// First node: catchAll node with empty path369		child := &node{370			wildChild: true,371			nType:     catchAll,372			fullPath:  fullPath,373		}374375		n.addChild(child)376		n.indices = "/"377		n = child378		n.priority++379380		// second node: node holding the variable381		child = &node{382			path:     path[i:],383			nType:    catchAll,384			handlers: handlers,385			priority: 1,386			fullPath: fullPath,387		}388		n.children = []*node{child}389390		return391	}392393	// If no wildcard was found, simply insert the path and handle394	n.path = path395	n.handlers = handlers396	n.fullPath = fullPath397}398399// nodeValue holds return values of (*Node).getValue method400type nodeValue struct {401	handlers HandlersChain402	params   *Params403	tsr      bool404	fullPath string405}406407type skippedNode struct {408	path        string409	node        *node410	paramsCount int16411}412413// Returns the handle registered with the given path (key). The values of414// wildcards are saved to a map.415// If no handle can be found, a TSR (trailing slash redirect) recommendation is416// made if a handle exists with an extra (without the) trailing slash for the417// given path.418func (n *node) getValue(path string, params *Params, skippedNodes *[]skippedNode, unescape bool) (value nodeValue) {419	var globalParamsCount int16420421	// Reset the skipped-nodes stack on entry. getValue is called once per422	// method tree (e.g. in the HandleMethodNotAllowed loop) reusing the same423	// pooled Context stack. Without this reset the residue from a previous424	// tree leaks into the next call. The walk grows the stack with append:425	// a context allocated before addRoute raised maxSections must still be426	// able to record one more backtrack frame. A raw reslice of the capacity427	// captured at pool allocation panics with "slice bounds out of range".428	*skippedNodes = (*skippedNodes)[:0]429430walk: // Outer loop for walking the tree431	for {432		prefix := n.path433		if len(path) > len(prefix) {434			if path[:len(prefix)] == prefix {435				path = path[len(prefix):]436437				// Try all the non-wildcard children first by matching the indices438				idxc := path[0]439				for i, c := range []byte(n.indices) {440					if c == idxc {441						//  strings.HasPrefix(n.children[len(n.children)-1].path, ":") == n.wildChild442						if n.wildChild {443							*skippedNodes = append(*skippedNodes, skippedNode{444								path: prefix + path,445								node: &node{446									path:      n.path,447									wildChild: n.wildChild,448									nType:     n.nType,449									priority:  n.priority,450									children:  n.children,451									handlers:  n.handlers,452									fullPath:  n.fullPath,453								},454								paramsCount: globalParamsCount,455							})456						}457458						n = n.children[i]459						continue walk460					}461				}462463				if !n.wildChild {464					// If the path at the end of the loop is not equal to '/' and the current node has no child nodes465					// the current node needs to roll back to last valid skippedNode466					if path != "/" {467						for length := len(*skippedNodes); length > 0; length-- {468							skippedNode := (*skippedNodes)[length-1]469							*skippedNodes = (*skippedNodes)[:length-1]470							if strings.HasSuffix(skippedNode.path, path) {471								path = skippedNode.path472								n = skippedNode.node473								if value.params != nil {474									*value.params = (*value.params)[:skippedNode.paramsCount]475								}476								globalParamsCount = skippedNode.paramsCount477								continue walk478							}479						}480					}481482					// Nothing found.483					// We can recommend to redirect to the same URL without a484					// trailing slash if a leaf exists for that path.485					value.tsr = path == "/" && n.handlers != nil486					return value487				}488489				// Handle wildcard child, which is always at the end of the array490				n = n.children[len(n.children)-1]491				globalParamsCount++492493				switch n.nType {494				case param:495					// fix truncate the parameter496					// tree_test.go  line: 204497498					// Find param end (either '/' or path end)499					end := 0500					for end < len(path) && path[end] != '/' {501						end++502					}503504					// Save param value505					if params != nil {506						// Preallocate capacity if necessary507						if cap(*params) < int(globalParamsCount) {508							newParams := make(Params, len(*params), globalParamsCount)509							copy(newParams, *params)510							*params = newParams511						}512513						if value.params == nil {514							value.params = params515						}516						// Expand slice within preallocated capacity517						i := len(*value.params)518						*value.params = (*value.params)[:i+1]519						val := path[:end]520						if unescape {521							if v, err := url.QueryUnescape(val); err == nil {522								val = v523							}524						}525						(*value.params)[i] = Param{526							Key:   n.path[1:],527							Value: val,528						}529					}530531					// we need to go deeper!532					if end < len(path) {533						if len(n.children) > 0 {534							path = path[end:]535							n = n.children[0]536							continue walk537						}538539						// ... but we can't540						value.tsr = len(path) == end+1541						return value542					}543544					if value.handlers = n.handlers; value.handlers != nil {545						value.fullPath = n.fullPath546						return value547					}548					if len(n.children) == 1 {549						// No handle found. Check if a handle for this path + a550						// trailing slash exists for TSR recommendation551						n = n.children[0]552						value.tsr = (n.path == "/" && n.handlers != nil) || (n.path == "" && n.indices == "/")553					}554					return value555556				case catchAll:557					// Save param value558					if params != nil {559						// Preallocate capacity if necessary560						if cap(*params) < int(globalParamsCount) {561							newParams := make(Params, len(*params), globalParamsCount)562							copy(newParams, *params)563							*params = newParams564						}565566						if value.params == nil {567							value.params = params568						}569						// Expand slice within preallocated capacity570						i := len(*value.params)571						*value.params = (*value.params)[:i+1]572						val := path573						if unescape {574							if v, err := url.QueryUnescape(path); err == nil {575								val = v576							}577						}578						(*value.params)[i] = Param{579							Key:   n.path[2:],580							Value: val,581						}582					}583584					value.handlers = n.handlers585					value.fullPath = n.fullPath586					return value587588				default:589					panic("invalid node type")590				}591			}592		}593594		if path == prefix {595			// If the current path does not equal '/' and the node does not have a registered handle and the most recently matched node has a child node596			// the current node needs to roll back to last valid skippedNode597			if n.handlers == nil && path != "/" {598				for length := len(*skippedNodes); length > 0; length-- {599					skippedNode := (*skippedNodes)[length-1]600					*skippedNodes = (*skippedNodes)[:length-1]601					if strings.HasSuffix(skippedNode.path, path) {602						path = skippedNode.path603						n = skippedNode.node604						if value.params != nil {605							*value.params = (*value.params)[:skippedNode.paramsCount]606						}607						globalParamsCount = skippedNode.paramsCount608						continue walk609					}610				}611				//	n = latestNode.children[len(latestNode.children)-1]612			}613			// We should have reached the node containing the handle.614			// Check if this node has a handle registered.615			if value.handlers = n.handlers; value.handlers != nil {616				value.fullPath = n.fullPath617				return value618			}619620			// If there is no handle for this route, but this route has a621			// wildcard child, there must be a handle for this path with an622			// additional trailing slash623			if path == "/" && n.wildChild && n.nType != root {624				value.tsr = true625				return value626			}627628			if path == "/" && n.nType == static {629				value.tsr = true630				return value631			}632633			// No handle found. Check if a handle for this path + a634			// trailing slash exists for trailing slash recommendation635			for i, c := range []byte(n.indices) {636				if c == '/' {637					n = n.children[i]638					value.tsr = (len(n.path) == 1 && n.handlers != nil) ||639						(n.nType == catchAll && n.children[0].handlers != nil)640					return value641				}642			}643644			return value645		}646647		// Nothing found. We can recommend to redirect to the same URL with an648		// extra trailing slash if a leaf exists for that path649		value.tsr = path == "/" ||650			(len(prefix) == len(path)+1 && prefix[len(path)] == '/' &&651				path == prefix[:len(prefix)-1] && n.handlers != nil)652653		// roll back to last valid skippedNode654		if !value.tsr && path != "/" {655			for length := len(*skippedNodes); length > 0; length-- {656				skippedNode := (*skippedNodes)[length-1]657				*skippedNodes = (*skippedNodes)[:length-1]658				if strings.HasSuffix(skippedNode.path, path) {659					path = skippedNode.path660					n = skippedNode.node661					if value.params != nil {662						*value.params = (*value.params)[:skippedNode.paramsCount]663					}664					globalParamsCount = skippedNode.paramsCount665					continue walk666				}667			}668		}669670		return value671	}672}673674// Makes a case-insensitive lookup of the given path and tries to find a handler.675// It can optionally also fix trailing slashes.676// It returns the case-corrected path and a bool indicating whether the lookup677// was successful.678func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) ([]byte, bool) {679	const stackBufSize = 128680681	buf := make([]byte, 0, max(stackBufSize, len(path)+1))682683	ciPath := n.findCaseInsensitivePathRec(684		path,685		buf,       // Preallocate enough memory for new path686		[4]byte{}, // Empty rune buffer687		fixTrailingSlash,688	)689690	return ciPath, ciPath != nil691}692693// shiftNRuneBytes shifts bytes in the array n positions to the left.694func shiftNRuneBytes(rb [4]byte, n int) [4]byte {695	switch n {696	case 0:697		return rb698	case 1:699		return [4]byte{rb[1], rb[2], rb[3], 0}700	case 2:701		return [4]byte{rb[2], rb[3]}702	case 3:703		return [4]byte{rb[3]}704	default:705		return [4]byte{}706	}707}708709// findCaseInsensitivePathRec recursively performs a case-insensitive path lookup.710func (n *node) findCaseInsensitivePathRec(path string, ciPath []byte, rb [4]byte, fixTrailingSlash bool) []byte {711	npLen := len(n.path)712713walk: // Outer loop for walking the tree714	for len(path) >= npLen && (npLen == 0 || strings.EqualFold(path[1:npLen], n.path[1:])) {715		// Add common prefix to result716		oldPath := path717		path = path[npLen:]718		ciPath = append(ciPath, n.path...)719720		if len(path) == 0 {721			// We should have reached the node containing the handle.722			// Check if this node has a handle registered.723			if n.handlers != nil {724				return ciPath725			}726727			// No handle found.728			// Try to fix the path by adding a trailing slash729			if fixTrailingSlash {730				for i, c := range []byte(n.indices) {731					if c == '/' {732						n = n.children[i]733						if (len(n.path) == 1 && n.handlers != nil) ||734							(n.nType == catchAll && n.children[0].handlers != nil) {735							return append(ciPath, '/')736						}737						return nil738					}739				}740			}741			return nil742		}743744		// If this node does not have a wildcard (param or catchAll) child,745		// we can just look up the next child node and continue to walk down746		// the tree747		if !n.wildChild {748			// Skip rune bytes already processed749			rb = shiftNRuneBytes(rb, npLen)750751			if rb[0] != 0 {752				// Old rune not finished753				idxc := rb[0]754				for i, c := range []byte(n.indices) {755					if c == idxc {756						// continue with child node757						n = n.children[i]758						npLen = len(n.path)759						continue walk760					}761				}762			} else {763				// Process a new rune764				var rv rune765766				// Find rune start.767				// Runes are up to 4 byte long,768				// -4 would definitely be another rune.769				var off int770				for max_ := min(npLen, 3); off < max_; off++ {771					if i := npLen - off; utf8.RuneStart(oldPath[i]) {772						// read rune from cached path773						rv, _ = utf8.DecodeRuneInString(oldPath[i:])774						break775					}776				}777778				// Calculate lowercase bytes of current rune779				lo := unicode.ToLower(rv)780				utf8.EncodeRune(rb[:], lo)781782				// Skip already processed bytes783				rb = shiftNRuneBytes(rb, off)784785				idxc := rb[0]786				for i, c := range []byte(n.indices) {787					// Lowercase matches788					if c == idxc {789						// must use a recursive approach since both the790						// uppercase byte and the lowercase byte might exist791						// as an index792						if out := n.children[i].findCaseInsensitivePathRec(793							path, ciPath, rb, fixTrailingSlash,794						); out != nil {795							return out796						}797						break798					}799				}800801				// If we found no match, the same for the uppercase rune,802				// if it differs803				if up := unicode.ToUpper(rv); up != lo {804					utf8.EncodeRune(rb[:], up)805					rb = shiftNRuneBytes(rb, off)806807					idxc := rb[0]808					for i, c := range []byte(n.indices) {809						// Uppercase matches810						if c == idxc {811							// Continue with child node812							n = n.children[i]813							npLen = len(n.path)814							continue walk815						}816					}817				}818			}819820			// Nothing found. We can recommend to redirect to the same URL821			// without a trailing slash if a leaf exists for that path822			if fixTrailingSlash && path == "/" && n.handlers != nil {823				return ciPath824			}825			return nil826		}827828		// When wildChild is true, try static children first (via indices)829		// before falling back to the wildcard child. This ensures that830		// case-insensitive lookups prefer static routes over param routes831		// (e.g., /PREFIX/XXX should resolve to /prefix/xxx, not match :id).832		if len(n.indices) > 0 {833			rb = shiftNRuneBytes(rb, npLen)834835			if rb[0] != 0 {836				idxc := rb[0]837				for i, c := range []byte(n.indices) {838					if c == idxc {839						if out := n.children[i].findCaseInsensitivePathRec(840							path, ciPath, rb, fixTrailingSlash,841						); out != nil {842							return out843						}844						break845					}846				}847			} else {848				var rv rune849				var off int850				for max_ := min(npLen, 3); off < max_; off++ {851					if i := npLen - off; utf8.RuneStart(oldPath[i]) {852						rv, _ = utf8.DecodeRuneInString(oldPath[i:])853						break854					}855				}856857				lo := unicode.ToLower(rv)858				utf8.EncodeRune(rb[:], lo)859				rb = shiftNRuneBytes(rb, off)860861				idxc := rb[0]862				for i, c := range []byte(n.indices) {863					if c == idxc {864						if out := n.children[i].findCaseInsensitivePathRec(865							path, ciPath, rb, fixTrailingSlash,866						); out != nil {867							return out868						}869						break870					}871				}872873				if up := unicode.ToUpper(rv); up != lo {874					utf8.EncodeRune(rb[:], up)875					rb = shiftNRuneBytes(rb, off)876877					idxc := rb[0]878					for i, c := range []byte(n.indices) {879						if c == idxc {880							if out := n.children[i].findCaseInsensitivePathRec(881								path, ciPath, rb, fixTrailingSlash,882							); out != nil {883								return out884							}885							break886						}887					}888				}889			}890		}891892		// Fall back to wildcard child, which is always at the end of the array893		n = n.children[len(n.children)-1]894		switch n.nType {895		case param:896			// Find param end (either '/' or path end)897			end := 0898			for end < len(path) && path[end] != '/' {899				end++900			}901902			// Add param value to case insensitive path903			ciPath = append(ciPath, path[:end]...)904905			// We need to go deeper!906			if end < len(path) {907				if len(n.children) > 0 {908					// Continue with child node909					n = n.children[0]910					npLen = len(n.path)911					path = path[end:]912					continue913				}914915				// ... but we can't916				if fixTrailingSlash && len(path) == end+1 {917					return ciPath918				}919				return nil920			}921922			if n.handlers != nil {923				return ciPath924			}925926			if fixTrailingSlash && len(n.children) == 1 {927				// No handle found. Check if a handle for this path + a928				// trailing slash exists929				n = n.children[0]930				if n.path == "/" && n.handlers != nil {931					return append(ciPath, '/')932				}933			}934935			return nil936937		case catchAll:938			return append(ciPath, path...)939940		default:941			panic("invalid node type")942		}943	}944945	// Nothing found.946	// Try to fix the path by adding / removing a trailing slash947	if fixTrailingSlash {948		if path == "/" {949			return ciPath950		}951		if len(path)+1 == npLen && n.path[len(path)] == '/' &&952			strings.EqualFold(path[1:], n.path[1:len(path)]) && n.handlers != nil {953			return append(ciPath, n.path...)954		}955	}956	return nil957}