tree.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867
  1. // Copyright 2013 Julien Schmidt. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be found
  3. // at https://github.com/julienschmidt/httprouter/blob/master/LICENSE
  4. package gin
  5. import (
  6. "bytes"
  7. "net/url"
  8. "strings"
  9. "unicode"
  10. "unicode/utf8"
  11. "github.com/gin-gonic/gin/internal/bytesconv"
  12. )
  13. var (
  14. strColon = []byte(":")
  15. strStar = []byte("*")
  16. strSlash = []byte("/")
  17. )
  18. // Param is a single URL parameter, consisting of a key and a value.
  19. type Param struct {
  20. Key string
  21. Value string
  22. }
  23. // Params is a Param-slice, as returned by the router.
  24. // The slice is ordered, the first URL parameter is also the first slice value.
  25. // It is therefore safe to read values by the index.
  26. type Params []Param
  27. // Get returns the value of the first Param which key matches the given name.
  28. // If no matching Param is found, an empty string is returned.
  29. func (ps Params) Get(name string) (string, bool) {
  30. for _, entry := range ps {
  31. if entry.Key == name {
  32. return entry.Value, true
  33. }
  34. }
  35. return "", false
  36. }
  37. // ByName returns the value of the first Param which key matches the given name.
  38. // If no matching Param is found, an empty string is returned.
  39. func (ps Params) ByName(name string) (va string) {
  40. va, _ = ps.Get(name)
  41. return
  42. }
  43. type methodTree struct {
  44. method string
  45. root *node
  46. }
  47. type methodTrees []methodTree
  48. func (trees methodTrees) get(method string) *node {
  49. for _, tree := range trees {
  50. if tree.method == method {
  51. return tree.root
  52. }
  53. }
  54. return nil
  55. }
  56. func min(a, b int) int {
  57. if a <= b {
  58. return a
  59. }
  60. return b
  61. }
  62. func longestCommonPrefix(a, b string) int {
  63. i := 0
  64. max := min(len(a), len(b))
  65. for i < max && a[i] == b[i] {
  66. i++
  67. }
  68. return i
  69. }
  70. // addChild will add a child node, keeping wildcards at the end
  71. func (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. }
  79. func countParams(path string) uint16 {
  80. var n uint16
  81. s := bytesconv.StringToBytes(path)
  82. n += uint16(bytes.Count(s, strColon))
  83. n += uint16(bytes.Count(s, strStar))
  84. return n
  85. }
  86. func countSections(path string) uint16 {
  87. s := bytesconv.StringToBytes(path)
  88. return uint16(bytes.Count(s, strSlash))
  89. }
  90. type nodeType uint8
  91. const (
  92. static nodeType = iota // default
  93. root
  94. param
  95. catchAll
  96. )
  97. type node struct {
  98. path string
  99. indices string
  100. wildChild bool
  101. nType nodeType
  102. priority uint32
  103. children []*node // child nodes, at most 1 :param style node at the end of the array
  104. handlers HandlersChain
  105. fullPath string
  106. }
  107. // Increments priority of the given child and reorders if necessary
  108. func (n *node) incrementChildPrio(pos int) int {
  109. cs := n.children
  110. cs[pos].priority++
  111. prio := cs[pos].priority
  112. // Adjust position (move to front)
  113. newPos := pos
  114. for ; newPos > 0 && cs[newPos-1].priority < prio; newPos-- {
  115. // Swap node positions
  116. cs[newPos-1], cs[newPos] = cs[newPos], cs[newPos-1]
  117. }
  118. // Build new index char string
  119. if newPos != pos {
  120. n.indices = n.indices[:newPos] + // Unchanged prefix, might be empty
  121. n.indices[pos:pos+1] + // The index char we move
  122. n.indices[newPos:pos] + n.indices[pos+1:] // Rest without char at 'pos'
  123. }
  124. return newPos
  125. }
  126. // addRoute adds a node with the given handle to the path.
  127. // Not concurrency-safe!
  128. func (n *node) addRoute(path string, handlers HandlersChain) {
  129. fullPath := path
  130. n.priority++
  131. // Empty tree
  132. if len(n.path) == 0 && len(n.children) == 0 {
  133. n.insertChild(path, fullPath, handlers)
  134. n.nType = root
  135. return
  136. }
  137. parentFullPathIndex := 0
  138. walk:
  139. for {
  140. // Find the longest common prefix.
  141. // This also implies that the common prefix contains no ':' or '*'
  142. // since the existing key can't contain those chars.
  143. i := longestCommonPrefix(path, n.path)
  144. // Split edge
  145. if i < len(n.path) {
  146. child := node{
  147. path: n.path[i:],
  148. wildChild: n.wildChild,
  149. indices: n.indices,
  150. children: n.children,
  151. handlers: n.handlers,
  152. priority: n.priority - 1,
  153. fullPath: n.fullPath,
  154. }
  155. n.children = []*node{&child}
  156. // []byte for proper unicode char conversion, see #65
  157. n.indices = bytesconv.BytesToString([]byte{n.path[i]})
  158. n.path = path[:i]
  159. n.handlers = nil
  160. n.wildChild = false
  161. n.fullPath = fullPath[:parentFullPathIndex+i]
  162. }
  163. // Make new node a child of this node
  164. if i < len(path) {
  165. path = path[i:]
  166. c := path[0]
  167. // '/' after param
  168. if n.nType == param && c == '/' && len(n.children) == 1 {
  169. parentFullPathIndex += len(n.path)
  170. n = n.children[0]
  171. n.priority++
  172. continue walk
  173. }
  174. // Check if a child with the next path byte exists
  175. for i, max := 0, len(n.indices); i < max; i++ {
  176. if c == n.indices[i] {
  177. parentFullPathIndex += len(n.path)
  178. i = n.incrementChildPrio(i)
  179. n = n.children[i]
  180. continue walk
  181. }
  182. }
  183. // Otherwise insert it
  184. if c != ':' && c != '*' && n.nType != catchAll {
  185. // []byte for proper unicode char conversion, see #65
  186. n.indices += bytesconv.BytesToString([]byte{c})
  187. child := &node{
  188. fullPath: fullPath,
  189. }
  190. n.addChild(child)
  191. n.incrementChildPrio(len(n.indices) - 1)
  192. n = child
  193. } else if n.wildChild {
  194. // inserting a wildcard node, need to check if it conflicts with the existing wildcard
  195. n = n.children[len(n.children)-1]
  196. n.priority++
  197. // Check if the wildcard matches
  198. if len(path) >= len(n.path) && n.path == path[:len(n.path)] &&
  199. // Adding a child to a catchAll is not possible
  200. n.nType != catchAll &&
  201. // Check for longer wildcard, e.g. :name and :names
  202. (len(n.path) >= len(path) || path[len(n.path)] == '/') {
  203. continue walk
  204. }
  205. // Wildcard conflict
  206. pathSeg := path
  207. if n.nType != catchAll {
  208. pathSeg = strings.SplitN(pathSeg, "/", 2)[0]
  209. }
  210. prefix := fullPath[:strings.Index(fullPath, pathSeg)] + n.path
  211. panic("'" + pathSeg +
  212. "' in new path '" + fullPath +
  213. "' conflicts with existing wildcard '" + n.path +
  214. "' in existing prefix '" + prefix +
  215. "'")
  216. }
  217. n.insertChild(path, fullPath, handlers)
  218. return
  219. }
  220. // Otherwise add handle to current node
  221. if n.handlers != nil {
  222. panic("handlers are already registered for path '" + fullPath + "'")
  223. }
  224. n.handlers = handlers
  225. n.fullPath = fullPath
  226. return
  227. }
  228. }
  229. // Search for a wildcard segment and check the name for invalid characters.
  230. // Returns -1 as index, if no wildcard was found.
  231. func findWildcard(path string) (wildcard string, i int, valid bool) {
  232. // Find start
  233. for start, c := range []byte(path) {
  234. // A wildcard starts with ':' (param) or '*' (catch-all)
  235. if c != ':' && c != '*' {
  236. continue
  237. }
  238. // Find end and check for invalid characters
  239. valid = true
  240. for end, c := range []byte(path[start+1:]) {
  241. switch c {
  242. case '/':
  243. return path[start : start+1+end], start, valid
  244. case ':', '*':
  245. valid = false
  246. }
  247. }
  248. return path[start:], start, valid
  249. }
  250. return "", -1, false
  251. }
  252. func (n *node) insertChild(path string, fullPath string, handlers HandlersChain) {
  253. for {
  254. // Find prefix until first wildcard
  255. wildcard, i, valid := findWildcard(path)
  256. if i < 0 { // No wildcard found
  257. break
  258. }
  259. // The wildcard name must not contain ':' and '*'
  260. if !valid {
  261. panic("only one wildcard per path segment is allowed, has: '" +
  262. wildcard + "' in path '" + fullPath + "'")
  263. }
  264. // check if the wildcard has a name
  265. if len(wildcard) < 2 {
  266. panic("wildcards must be named with a non-empty name in path '" + fullPath + "'")
  267. }
  268. if wildcard[0] == ':' { // param
  269. if i > 0 {
  270. // Insert prefix before the current wildcard
  271. n.path = path[:i]
  272. path = path[i:]
  273. }
  274. child := &node{
  275. nType: param,
  276. path: wildcard,
  277. fullPath: fullPath,
  278. }
  279. n.addChild(child)
  280. n.wildChild = true
  281. n = child
  282. n.priority++
  283. // if the path doesn't end with the wildcard, then there
  284. // will be another non-wildcard subpath starting with '/'
  285. if len(wildcard) < len(path) {
  286. path = path[len(wildcard):]
  287. child := &node{
  288. priority: 1,
  289. fullPath: fullPath,
  290. }
  291. n.addChild(child)
  292. n = child
  293. continue
  294. }
  295. // Otherwise we're done. Insert the handle in the new leaf
  296. n.handlers = handlers
  297. return
  298. }
  299. // catchAll
  300. if i+len(wildcard) != len(path) {
  301. panic("catch-all routes are only allowed at the end of the path in path '" + fullPath + "'")
  302. }
  303. if len(n.path) > 0 && n.path[len(n.path)-1] == '/' {
  304. panic("catch-all conflicts with existing handle for the path segment root in path '" + fullPath + "'")
  305. }
  306. // currently fixed width 1 for '/'
  307. i--
  308. if path[i] != '/' {
  309. panic("no / before catch-all in path '" + fullPath + "'")
  310. }
  311. n.path = path[:i]
  312. // First node: catchAll node with empty path
  313. child := &node{
  314. wildChild: true,
  315. nType: catchAll,
  316. fullPath: fullPath,
  317. }
  318. n.addChild(child)
  319. n.indices = string('/')
  320. n = child
  321. n.priority++
  322. // second node: node holding the variable
  323. child = &node{
  324. path: path[i:],
  325. nType: catchAll,
  326. handlers: handlers,
  327. priority: 1,
  328. fullPath: fullPath,
  329. }
  330. n.children = []*node{child}
  331. return
  332. }
  333. // If no wildcard was found, simply insert the path and handle
  334. n.path = path
  335. n.handlers = handlers
  336. n.fullPath = fullPath
  337. }
  338. // nodeValue holds return values of (*Node).getValue method
  339. type nodeValue struct {
  340. handlers HandlersChain
  341. params *Params
  342. tsr bool
  343. fullPath string
  344. }
  345. type skippedNode struct {
  346. path string
  347. node *node
  348. paramsCount int16
  349. }
  350. // Returns the handle registered with the given path (key). The values of
  351. // wildcards are saved to a map.
  352. // If no handle can be found, a TSR (trailing slash redirect) recommendation is
  353. // made if a handle exists with an extra (without the) trailing slash for the
  354. // given path.
  355. func (n *node) getValue(path string, params *Params, skippedNodes *[]skippedNode, unescape bool) (value nodeValue) {
  356. var globalParamsCount int16
  357. walk: // Outer loop for walking the tree
  358. for {
  359. prefix := n.path
  360. if len(path) > len(prefix) {
  361. if path[:len(prefix)] == prefix {
  362. path = path[len(prefix):]
  363. // Try all the non-wildcard children first by matching the indices
  364. idxc := path[0]
  365. for i, c := range []byte(n.indices) {
  366. if c == idxc {
  367. // strings.HasPrefix(n.children[len(n.children)-1].path, ":") == n.wildChild
  368. if n.wildChild {
  369. index := len(*skippedNodes)
  370. *skippedNodes = (*skippedNodes)[:index+1]
  371. (*skippedNodes)[index] = skippedNode{
  372. path: prefix + path,
  373. node: &node{
  374. path: n.path,
  375. wildChild: n.wildChild,
  376. nType: n.nType,
  377. priority: n.priority,
  378. children: n.children,
  379. handlers: n.handlers,
  380. fullPath: n.fullPath,
  381. },
  382. paramsCount: globalParamsCount,
  383. }
  384. }
  385. n = n.children[i]
  386. continue walk
  387. }
  388. }
  389. if !n.wildChild {
  390. // If the path at the end of the loop is not equal to '/' and the current node has no child nodes
  391. // the current node needs to roll back to last vaild skippedNode
  392. if path != "/" {
  393. for l := len(*skippedNodes); l > 0; {
  394. skippedNode := (*skippedNodes)[l-1]
  395. *skippedNodes = (*skippedNodes)[:l-1]
  396. if strings.HasSuffix(skippedNode.path, path) {
  397. path = skippedNode.path
  398. n = skippedNode.node
  399. if value.params != nil {
  400. *value.params = (*value.params)[:skippedNode.paramsCount]
  401. }
  402. globalParamsCount = skippedNode.paramsCount
  403. continue walk
  404. }
  405. }
  406. }
  407. // Nothing found.
  408. // We can recommend to redirect to the same URL without a
  409. // trailing slash if a leaf exists for that path.
  410. value.tsr = path == "/" && n.handlers != nil
  411. return
  412. }
  413. // Handle wildcard child, which is always at the end of the array
  414. n = n.children[len(n.children)-1]
  415. globalParamsCount++
  416. switch n.nType {
  417. case param:
  418. // fix truncate the parameter
  419. // tree_test.go line: 204
  420. // Find param end (either '/' or path end)
  421. end := 0
  422. for end < len(path) && path[end] != '/' {
  423. end++
  424. }
  425. // Save param value
  426. if params != nil && cap(*params) > 0 {
  427. if value.params == nil {
  428. value.params = params
  429. }
  430. // Expand slice within preallocated capacity
  431. i := len(*value.params)
  432. *value.params = (*value.params)[:i+1]
  433. val := path[:end]
  434. if unescape {
  435. if v, err := url.QueryUnescape(val); err == nil {
  436. val = v
  437. }
  438. }
  439. (*value.params)[i] = Param{
  440. Key: n.path[1:],
  441. Value: val,
  442. }
  443. }
  444. // we need to go deeper!
  445. if end < len(path) {
  446. if len(n.children) > 0 {
  447. path = path[end:]
  448. n = n.children[0]
  449. continue walk
  450. }
  451. // ... but we can't
  452. value.tsr = len(path) == end+1
  453. return
  454. }
  455. if value.handlers = n.handlers; value.handlers != nil {
  456. value.fullPath = n.fullPath
  457. return
  458. }
  459. if len(n.children) == 1 {
  460. // No handle found. Check if a handle for this path + a
  461. // trailing slash exists for TSR recommendation
  462. n = n.children[0]
  463. value.tsr = n.path == "/" && n.handlers != nil
  464. }
  465. return
  466. case catchAll:
  467. // Save param value
  468. if params != nil {
  469. if value.params == nil {
  470. value.params = params
  471. }
  472. // Expand slice within preallocated capacity
  473. i := len(*value.params)
  474. *value.params = (*value.params)[:i+1]
  475. val := path
  476. if unescape {
  477. if v, err := url.QueryUnescape(path); err == nil {
  478. val = v
  479. }
  480. }
  481. (*value.params)[i] = Param{
  482. Key: n.path[2:],
  483. Value: val,
  484. }
  485. }
  486. value.handlers = n.handlers
  487. value.fullPath = n.fullPath
  488. return
  489. default:
  490. panic("invalid node type")
  491. }
  492. }
  493. }
  494. if path == prefix {
  495. // 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 node
  496. // the current node needs to roll back to last vaild skippedNode
  497. if n.handlers == nil && path != "/" {
  498. for l := len(*skippedNodes); l > 0; {
  499. skippedNode := (*skippedNodes)[l-1]
  500. *skippedNodes = (*skippedNodes)[:l-1]
  501. if strings.HasSuffix(skippedNode.path, path) {
  502. path = skippedNode.path
  503. n = skippedNode.node
  504. if value.params != nil {
  505. *value.params = (*value.params)[:skippedNode.paramsCount]
  506. }
  507. globalParamsCount = skippedNode.paramsCount
  508. continue walk
  509. }
  510. }
  511. // n = latestNode.children[len(latestNode.children)-1]
  512. }
  513. // We should have reached the node containing the handle.
  514. // Check if this node has a handle registered.
  515. if value.handlers = n.handlers; value.handlers != nil {
  516. value.fullPath = n.fullPath
  517. return
  518. }
  519. // If there is no handle for this route, but this route has a
  520. // wildcard child, there must be a handle for this path with an
  521. // additional trailing slash
  522. if path == "/" && n.wildChild && n.nType != root {
  523. value.tsr = true
  524. return
  525. }
  526. // No handle found. Check if a handle for this path + a
  527. // trailing slash exists for trailing slash recommendation
  528. for i, c := range []byte(n.indices) {
  529. if c == '/' {
  530. n = n.children[i]
  531. value.tsr = (len(n.path) == 1 && n.handlers != nil) ||
  532. (n.nType == catchAll && n.children[0].handlers != nil)
  533. return
  534. }
  535. }
  536. return
  537. }
  538. // Nothing found. We can recommend to redirect to the same URL with an
  539. // extra trailing slash if a leaf exists for that path
  540. value.tsr = path == "/" ||
  541. (len(prefix) == len(path)+1 && prefix[len(path)] == '/' &&
  542. path == prefix[:len(prefix)-1] && n.handlers != nil)
  543. // roll back to last valid skippedNode
  544. if !value.tsr && path != "/" {
  545. for l := len(*skippedNodes); l > 0; {
  546. skippedNode := (*skippedNodes)[l-1]
  547. *skippedNodes = (*skippedNodes)[:l-1]
  548. if strings.HasSuffix(skippedNode.path, path) {
  549. path = skippedNode.path
  550. n = skippedNode.node
  551. if value.params != nil {
  552. *value.params = (*value.params)[:skippedNode.paramsCount]
  553. }
  554. globalParamsCount = skippedNode.paramsCount
  555. continue walk
  556. }
  557. }
  558. }
  559. return
  560. }
  561. }
  562. // Makes a case-insensitive lookup of the given path and tries to find a handler.
  563. // It can optionally also fix trailing slashes.
  564. // It returns the case-corrected path and a bool indicating whether the lookup
  565. // was successful.
  566. func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) ([]byte, bool) {
  567. const stackBufSize = 128
  568. // Use a static sized buffer on the stack in the common case.
  569. // If the path is too long, allocate a buffer on the heap instead.
  570. buf := make([]byte, 0, stackBufSize)
  571. if length := len(path) + 1; length > stackBufSize {
  572. buf = make([]byte, 0, length)
  573. }
  574. ciPath := n.findCaseInsensitivePathRec(
  575. path,
  576. buf, // Preallocate enough memory for new path
  577. [4]byte{}, // Empty rune buffer
  578. fixTrailingSlash,
  579. )
  580. return ciPath, ciPath != nil
  581. }
  582. // Shift bytes in array by n bytes left
  583. func shiftNRuneBytes(rb [4]byte, n int) [4]byte {
  584. switch n {
  585. case 0:
  586. return rb
  587. case 1:
  588. return [4]byte{rb[1], rb[2], rb[3], 0}
  589. case 2:
  590. return [4]byte{rb[2], rb[3]}
  591. case 3:
  592. return [4]byte{rb[3]}
  593. default:
  594. return [4]byte{}
  595. }
  596. }
  597. // Recursive case-insensitive lookup function used by n.findCaseInsensitivePath
  598. func (n *node) findCaseInsensitivePathRec(path string, ciPath []byte, rb [4]byte, fixTrailingSlash bool) []byte {
  599. npLen := len(n.path)
  600. walk: // Outer loop for walking the tree
  601. for len(path) >= npLen && (npLen == 0 || strings.EqualFold(path[1:npLen], n.path[1:])) {
  602. // Add common prefix to result
  603. oldPath := path
  604. path = path[npLen:]
  605. ciPath = append(ciPath, n.path...)
  606. if len(path) == 0 {
  607. // We should have reached the node containing the handle.
  608. // Check if this node has a handle registered.
  609. if n.handlers != nil {
  610. return ciPath
  611. }
  612. // No handle found.
  613. // Try to fix the path by adding a trailing slash
  614. if fixTrailingSlash {
  615. for i, c := range []byte(n.indices) {
  616. if c == '/' {
  617. n = n.children[i]
  618. if (len(n.path) == 1 && n.handlers != nil) ||
  619. (n.nType == catchAll && n.children[0].handlers != nil) {
  620. return append(ciPath, '/')
  621. }
  622. return nil
  623. }
  624. }
  625. }
  626. return nil
  627. }
  628. // If this node does not have a wildcard (param or catchAll) child,
  629. // we can just look up the next child node and continue to walk down
  630. // the tree
  631. if !n.wildChild {
  632. // Skip rune bytes already processed
  633. rb = shiftNRuneBytes(rb, npLen)
  634. if rb[0] != 0 {
  635. // Old rune not finished
  636. idxc := rb[0]
  637. for i, c := range []byte(n.indices) {
  638. if c == idxc {
  639. // continue with child node
  640. n = n.children[i]
  641. npLen = len(n.path)
  642. continue walk
  643. }
  644. }
  645. } else {
  646. // Process a new rune
  647. var rv rune
  648. // Find rune start.
  649. // Runes are up to 4 byte long,
  650. // -4 would definitely be another rune.
  651. var off int
  652. for max := min(npLen, 3); off < max; off++ {
  653. if i := npLen - off; utf8.RuneStart(oldPath[i]) {
  654. // read rune from cached path
  655. rv, _ = utf8.DecodeRuneInString(oldPath[i:])
  656. break
  657. }
  658. }
  659. // Calculate lowercase bytes of current rune
  660. lo := unicode.ToLower(rv)
  661. utf8.EncodeRune(rb[:], lo)
  662. // Skip already processed bytes
  663. rb = shiftNRuneBytes(rb, off)
  664. idxc := rb[0]
  665. for i, c := range []byte(n.indices) {
  666. // Lowercase matches
  667. if c == idxc {
  668. // must use a recursive approach since both the
  669. // uppercase byte and the lowercase byte might exist
  670. // as an index
  671. if out := n.children[i].findCaseInsensitivePathRec(
  672. path, ciPath, rb, fixTrailingSlash,
  673. ); out != nil {
  674. return out
  675. }
  676. break
  677. }
  678. }
  679. // If we found no match, the same for the uppercase rune,
  680. // if it differs
  681. if up := unicode.ToUpper(rv); up != lo {
  682. utf8.EncodeRune(rb[:], up)
  683. rb = shiftNRuneBytes(rb, off)
  684. idxc := rb[0]
  685. for i, c := range []byte(n.indices) {
  686. // Uppercase matches
  687. if c == idxc {
  688. // Continue with child node
  689. n = n.children[i]
  690. npLen = len(n.path)
  691. continue walk
  692. }
  693. }
  694. }
  695. }
  696. // Nothing found. We can recommend to redirect to the same URL
  697. // without a trailing slash if a leaf exists for that path
  698. if fixTrailingSlash && path == "/" && n.handlers != nil {
  699. return ciPath
  700. }
  701. return nil
  702. }
  703. n = n.children[0]
  704. switch n.nType {
  705. case param:
  706. // Find param end (either '/' or path end)
  707. end := 0
  708. for end < len(path) && path[end] != '/' {
  709. end++
  710. }
  711. // Add param value to case insensitive path
  712. ciPath = append(ciPath, path[:end]...)
  713. // We need to go deeper!
  714. if end < len(path) {
  715. if len(n.children) > 0 {
  716. // Continue with child node
  717. n = n.children[0]
  718. npLen = len(n.path)
  719. path = path[end:]
  720. continue
  721. }
  722. // ... but we can't
  723. if fixTrailingSlash && len(path) == end+1 {
  724. return ciPath
  725. }
  726. return nil
  727. }
  728. if n.handlers != nil {
  729. return ciPath
  730. }
  731. if fixTrailingSlash && len(n.children) == 1 {
  732. // No handle found. Check if a handle for this path + a
  733. // trailing slash exists
  734. n = n.children[0]
  735. if n.path == "/" && n.handlers != nil {
  736. return append(ciPath, '/')
  737. }
  738. }
  739. return nil
  740. case catchAll:
  741. return append(ciPath, path...)
  742. default:
  743. panic("invalid node type")
  744. }
  745. }
  746. // Nothing found.
  747. // Try to fix the path by adding / removing a trailing slash
  748. if fixTrailingSlash {
  749. if path == "/" {
  750. return ciPath
  751. }
  752. if len(path)+1 == npLen && n.path[len(path)] == '/' &&
  753. strings.EqualFold(path[1:], n.path[1:len(path)]) && n.handlers != nil {
  754. return append(ciPath, n.path...)
  755. }
  756. }
  757. return nil
  758. }