tree.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  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 and a boolean true.
  28. // If no matching Param is found, an empty string is returned and a boolean false .
  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 wildcardChild 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
  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. nType: static,
  150. indices: n.indices,
  151. children: n.children,
  152. handlers: n.handlers,
  153. priority: n.priority - 1,
  154. fullPath: n.fullPath,
  155. }
  156. n.children = []*node{&child}
  157. // []byte for proper unicode char conversion, see #65
  158. n.indices = bytesconv.BytesToString([]byte{n.path[i]})
  159. n.path = path[:i]
  160. n.handlers = nil
  161. n.wildChild = false
  162. n.fullPath = fullPath[:parentFullPathIndex+i]
  163. }
  164. // Make new node a child of this node
  165. if i < len(path) {
  166. path = path[i:]
  167. c := path[0]
  168. // '/' after param
  169. if n.nType == param && c == '/' && len(n.children) == 1 {
  170. parentFullPathIndex += len(n.path)
  171. n = n.children[0]
  172. n.priority++
  173. continue walk
  174. }
  175. // Check if a child with the next path byte exists
  176. for i, max := 0, len(n.indices); i < max; i++ {
  177. if c == n.indices[i] {
  178. parentFullPathIndex += len(n.path)
  179. i = n.incrementChildPrio(i)
  180. n = n.children[i]
  181. continue walk
  182. }
  183. }
  184. // Otherwise insert it
  185. if c != ':' && c != '*' && n.nType != catchAll {
  186. // []byte for proper unicode char conversion, see #65
  187. n.indices += bytesconv.BytesToString([]byte{c})
  188. child := &node{
  189. fullPath: fullPath,
  190. }
  191. n.addChild(child)
  192. n.incrementChildPrio(len(n.indices) - 1)
  193. n = child
  194. } else if n.wildChild {
  195. // inserting a wildcard node, need to check if it conflicts with the existing wildcard
  196. n = n.children[len(n.children)-1]
  197. n.priority++
  198. // Check if the wildcard matches
  199. if len(path) >= len(n.path) && n.path == path[:len(n.path)] &&
  200. // Adding a child to a catchAll is not possible
  201. n.nType != catchAll &&
  202. // Check for longer wildcard, e.g. :name and :names
  203. (len(n.path) >= len(path) || path[len(n.path)] == '/') {
  204. continue walk
  205. }
  206. // Wildcard conflict
  207. pathSeg := path
  208. if n.nType != catchAll {
  209. pathSeg = strings.SplitN(pathSeg, "/", 2)[0]
  210. }
  211. prefix := fullPath[:strings.Index(fullPath, pathSeg)] + n.path
  212. panic("'" + pathSeg +
  213. "' in new path '" + fullPath +
  214. "' conflicts with existing wildcard '" + n.path +
  215. "' in existing prefix '" + prefix +
  216. "'")
  217. }
  218. n.insertChild(path, fullPath, handlers)
  219. return
  220. }
  221. // Otherwise add handle to current node
  222. if n.handlers != nil {
  223. panic("handlers are already registered for path '" + fullPath + "'")
  224. }
  225. n.handlers = handlers
  226. n.fullPath = fullPath
  227. return
  228. }
  229. }
  230. // Search for a wildcard segment and check the name for invalid characters.
  231. // Returns -1 as index, if no wildcard was found.
  232. func findWildcard(path string) (wildcard string, i int, valid bool) {
  233. // Find start
  234. for start, c := range []byte(path) {
  235. // A wildcard starts with ':' (param) or '*' (catch-all)
  236. if c != ':' && c != '*' {
  237. continue
  238. }
  239. // Find end and check for invalid characters
  240. valid = true
  241. for end, c := range []byte(path[start+1:]) {
  242. switch c {
  243. case '/':
  244. return path[start : start+1+end], start, valid
  245. case ':', '*':
  246. valid = false
  247. }
  248. }
  249. return path[start:], start, valid
  250. }
  251. return "", -1, false
  252. }
  253. func (n *node) insertChild(path string, fullPath string, handlers HandlersChain) {
  254. for {
  255. // Find prefix until first wildcard
  256. wildcard, i, valid := findWildcard(path)
  257. if i < 0 { // No wildcard found
  258. break
  259. }
  260. // The wildcard name must only contain one ':' or '*' character
  261. if !valid {
  262. panic("only one wildcard per path segment is allowed, has: '" +
  263. wildcard + "' in path '" + fullPath + "'")
  264. }
  265. // check if the wildcard has a name
  266. if len(wildcard) < 2 {
  267. panic("wildcards must be named with a non-empty name in path '" + fullPath + "'")
  268. }
  269. if wildcard[0] == ':' { // param
  270. if i > 0 {
  271. // Insert prefix before the current wildcard
  272. n.path = path[:i]
  273. path = path[i:]
  274. }
  275. child := &node{
  276. nType: param,
  277. path: wildcard,
  278. fullPath: fullPath,
  279. }
  280. n.addChild(child)
  281. n.wildChild = true
  282. n = child
  283. n.priority++
  284. // if the path doesn't end with the wildcard, then there
  285. // will be another subpath starting with '/'
  286. if len(wildcard) < len(path) {
  287. path = path[len(wildcard):]
  288. child := &node{
  289. priority: 1,
  290. fullPath: fullPath,
  291. }
  292. n.addChild(child)
  293. n = child
  294. continue
  295. }
  296. // Otherwise we're done. Insert the handle in the new leaf
  297. n.handlers = handlers
  298. return
  299. }
  300. // catchAll
  301. if i+len(wildcard) != len(path) {
  302. panic("catch-all routes are only allowed at the end of the path in path '" + fullPath + "'")
  303. }
  304. if len(n.path) > 0 && n.path[len(n.path)-1] == '/' {
  305. pathSeg := ""
  306. if len(n.children) != 0 {
  307. pathSeg = strings.SplitN(n.children[0].path, "/", 2)[0]
  308. }
  309. panic("catch-all wildcard '" + path +
  310. "' in new path '" + fullPath +
  311. "' conflicts with existing path segment '" + pathSeg +
  312. "' in existing prefix '" + n.path + pathSeg +
  313. "'")
  314. }
  315. // currently fixed width 1 for '/'
  316. i--
  317. if path[i] != '/' {
  318. panic("no / before catch-all in path '" + fullPath + "'")
  319. }
  320. n.path = path[:i]
  321. // First node: catchAll node with empty path
  322. child := &node{
  323. wildChild: true,
  324. nType: catchAll,
  325. fullPath: fullPath,
  326. }
  327. n.addChild(child)
  328. n.indices = string('/')
  329. n = child
  330. n.priority++
  331. // second node: node holding the variable
  332. child = &node{
  333. path: path[i:],
  334. nType: catchAll,
  335. handlers: handlers,
  336. priority: 1,
  337. fullPath: fullPath,
  338. }
  339. n.children = []*node{child}
  340. return
  341. }
  342. // If no wildcard was found, simply insert the path and handle
  343. n.path = path
  344. n.handlers = handlers
  345. n.fullPath = fullPath
  346. }
  347. // nodeValue holds return values of (*Node).getValue method
  348. type nodeValue struct {
  349. handlers HandlersChain
  350. params *Params
  351. tsr bool
  352. fullPath string
  353. }
  354. type skippedNode struct {
  355. path string
  356. node *node
  357. paramsCount int16
  358. }
  359. // Returns the handle registered with the given path (key). The values of
  360. // wildcards are saved to a map.
  361. // If no handle can be found, a TSR (trailing slash redirect) recommendation is
  362. // made if a handle exists with an extra (without the) trailing slash for the
  363. // given path.
  364. func (n *node) getValue(path string, params *Params, skippedNodes *[]skippedNode, unescape bool) (value nodeValue) {
  365. var globalParamsCount int16
  366. walk: // Outer loop for walking the tree
  367. for {
  368. prefix := n.path
  369. if len(path) > len(prefix) {
  370. if path[:len(prefix)] == prefix {
  371. path = path[len(prefix):]
  372. // Try all the non-wildcard children first by matching the indices
  373. idxc := path[0]
  374. for i, c := range []byte(n.indices) {
  375. if c == idxc {
  376. // strings.HasPrefix(n.children[len(n.children)-1].path, ":") == n.wildChild
  377. if n.wildChild {
  378. index := len(*skippedNodes)
  379. *skippedNodes = (*skippedNodes)[:index+1]
  380. (*skippedNodes)[index] = skippedNode{
  381. path: prefix + path,
  382. node: &node{
  383. path: n.path,
  384. wildChild: n.wildChild,
  385. nType: n.nType,
  386. priority: n.priority,
  387. children: n.children,
  388. handlers: n.handlers,
  389. fullPath: n.fullPath,
  390. },
  391. paramsCount: globalParamsCount,
  392. }
  393. }
  394. n = n.children[i]
  395. continue walk
  396. }
  397. }
  398. if !n.wildChild {
  399. // If the path at the end of the loop is not equal to '/' and the current node has no child nodes
  400. // the current node needs to roll back to last valid skippedNode
  401. if path != "/" {
  402. for length := len(*skippedNodes); length > 0; length-- {
  403. skippedNode := (*skippedNodes)[length-1]
  404. *skippedNodes = (*skippedNodes)[:length-1]
  405. if strings.HasSuffix(skippedNode.path, path) {
  406. path = skippedNode.path
  407. n = skippedNode.node
  408. if value.params != nil {
  409. *value.params = (*value.params)[:skippedNode.paramsCount]
  410. }
  411. globalParamsCount = skippedNode.paramsCount
  412. continue walk
  413. }
  414. }
  415. }
  416. // Nothing found.
  417. // We can recommend to redirect to the same URL without a
  418. // trailing slash if a leaf exists for that path.
  419. value.tsr = path == "/" && n.handlers != nil
  420. return value
  421. }
  422. // Handle wildcard child, which is always at the end of the array
  423. n = n.children[len(n.children)-1]
  424. globalParamsCount++
  425. switch n.nType {
  426. case param:
  427. // fix truncate the parameter
  428. // tree_test.go line: 204
  429. // Find param end (either '/' or path end)
  430. end := 0
  431. for end < len(path) && path[end] != '/' {
  432. end++
  433. }
  434. // Save param value
  435. if params != nil {
  436. // Preallocate capacity if necessary
  437. if cap(*params) < int(globalParamsCount) {
  438. newParams := make(Params, len(*params), globalParamsCount)
  439. copy(newParams, *params)
  440. *params = newParams
  441. }
  442. if value.params == nil {
  443. value.params = params
  444. }
  445. // Expand slice within preallocated capacity
  446. i := len(*value.params)
  447. *value.params = (*value.params)[:i+1]
  448. val := path[:end]
  449. if unescape {
  450. if v, err := url.QueryUnescape(val); err == nil {
  451. val = v
  452. }
  453. }
  454. (*value.params)[i] = Param{
  455. Key: n.path[1:],
  456. Value: val,
  457. }
  458. }
  459. // we need to go deeper!
  460. if end < len(path) {
  461. if len(n.children) > 0 {
  462. path = path[end:]
  463. n = n.children[0]
  464. continue walk
  465. }
  466. // ... but we can't
  467. value.tsr = len(path) == end+1
  468. return value
  469. }
  470. if value.handlers = n.handlers; value.handlers != nil {
  471. value.fullPath = n.fullPath
  472. return value
  473. }
  474. if len(n.children) == 1 {
  475. // No handle found. Check if a handle for this path + a
  476. // trailing slash exists for TSR recommendation
  477. n = n.children[0]
  478. value.tsr = (n.path == "/" && n.handlers != nil) || (n.path == "" && n.indices == "/")
  479. }
  480. return value
  481. case catchAll:
  482. // Save param value
  483. if params != nil {
  484. // Preallocate capacity if necessary
  485. if cap(*params) < int(globalParamsCount) {
  486. newParams := make(Params, len(*params), globalParamsCount)
  487. copy(newParams, *params)
  488. *params = newParams
  489. }
  490. if value.params == nil {
  491. value.params = params
  492. }
  493. // Expand slice within preallocated capacity
  494. i := len(*value.params)
  495. *value.params = (*value.params)[:i+1]
  496. val := path
  497. if unescape {
  498. if v, err := url.QueryUnescape(path); err == nil {
  499. val = v
  500. }
  501. }
  502. (*value.params)[i] = Param{
  503. Key: n.path[2:],
  504. Value: val,
  505. }
  506. }
  507. value.handlers = n.handlers
  508. value.fullPath = n.fullPath
  509. return value
  510. default:
  511. panic("invalid node type")
  512. }
  513. }
  514. }
  515. if path == prefix {
  516. // 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
  517. // the current node needs to roll back to last valid skippedNode
  518. if n.handlers == nil && path != "/" {
  519. for length := len(*skippedNodes); length > 0; length-- {
  520. skippedNode := (*skippedNodes)[length-1]
  521. *skippedNodes = (*skippedNodes)[:length-1]
  522. if strings.HasSuffix(skippedNode.path, path) {
  523. path = skippedNode.path
  524. n = skippedNode.node
  525. if value.params != nil {
  526. *value.params = (*value.params)[:skippedNode.paramsCount]
  527. }
  528. globalParamsCount = skippedNode.paramsCount
  529. continue walk
  530. }
  531. }
  532. // n = latestNode.children[len(latestNode.children)-1]
  533. }
  534. // We should have reached the node containing the handle.
  535. // Check if this node has a handle registered.
  536. if value.handlers = n.handlers; value.handlers != nil {
  537. value.fullPath = n.fullPath
  538. return value
  539. }
  540. // If there is no handle for this route, but this route has a
  541. // wildcard child, there must be a handle for this path with an
  542. // additional trailing slash
  543. if path == "/" && n.wildChild && n.nType != root {
  544. value.tsr = true
  545. return value
  546. }
  547. if path == "/" && n.nType == static {
  548. value.tsr = true
  549. return value
  550. }
  551. // No handle found. Check if a handle for this path + a
  552. // trailing slash exists for trailing slash recommendation
  553. for i, c := range []byte(n.indices) {
  554. if c == '/' {
  555. n = n.children[i]
  556. value.tsr = (len(n.path) == 1 && n.handlers != nil) ||
  557. (n.nType == catchAll && n.children[0].handlers != nil)
  558. return value
  559. }
  560. }
  561. return value
  562. }
  563. // Nothing found. We can recommend to redirect to the same URL with an
  564. // extra trailing slash if a leaf exists for that path
  565. value.tsr = path == "/" ||
  566. (len(prefix) == len(path)+1 && prefix[len(path)] == '/' &&
  567. path == prefix[:len(prefix)-1] && n.handlers != nil)
  568. // roll back to last valid skippedNode
  569. if !value.tsr && path != "/" {
  570. for length := len(*skippedNodes); length > 0; length-- {
  571. skippedNode := (*skippedNodes)[length-1]
  572. *skippedNodes = (*skippedNodes)[:length-1]
  573. if strings.HasSuffix(skippedNode.path, path) {
  574. path = skippedNode.path
  575. n = skippedNode.node
  576. if value.params != nil {
  577. *value.params = (*value.params)[:skippedNode.paramsCount]
  578. }
  579. globalParamsCount = skippedNode.paramsCount
  580. continue walk
  581. }
  582. }
  583. }
  584. return value
  585. }
  586. }
  587. // Makes a case-insensitive lookup of the given path and tries to find a handler.
  588. // It can optionally also fix trailing slashes.
  589. // It returns the case-corrected path and a bool indicating whether the lookup
  590. // was successful.
  591. func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) ([]byte, bool) {
  592. const stackBufSize = 128
  593. // Use a static sized buffer on the stack in the common case.
  594. // If the path is too long, allocate a buffer on the heap instead.
  595. buf := make([]byte, 0, stackBufSize)
  596. if length := len(path) + 1; length > stackBufSize {
  597. buf = make([]byte, 0, length)
  598. }
  599. ciPath := n.findCaseInsensitivePathRec(
  600. path,
  601. buf, // Preallocate enough memory for new path
  602. [4]byte{}, // Empty rune buffer
  603. fixTrailingSlash,
  604. )
  605. return ciPath, ciPath != nil
  606. }
  607. // Shift bytes in array by n bytes left
  608. func shiftNRuneBytes(rb [4]byte, n int) [4]byte {
  609. switch n {
  610. case 0:
  611. return rb
  612. case 1:
  613. return [4]byte{rb[1], rb[2], rb[3], 0}
  614. case 2:
  615. return [4]byte{rb[2], rb[3]}
  616. case 3:
  617. return [4]byte{rb[3]}
  618. default:
  619. return [4]byte{}
  620. }
  621. }
  622. // Recursive case-insensitive lookup function used by n.findCaseInsensitivePath
  623. func (n *node) findCaseInsensitivePathRec(path string, ciPath []byte, rb [4]byte, fixTrailingSlash bool) []byte {
  624. npLen := len(n.path)
  625. walk: // Outer loop for walking the tree
  626. for len(path) >= npLen && (npLen == 0 || strings.EqualFold(path[1:npLen], n.path[1:])) {
  627. // Add common prefix to result
  628. oldPath := path
  629. path = path[npLen:]
  630. ciPath = append(ciPath, n.path...)
  631. if len(path) == 0 {
  632. // We should have reached the node containing the handle.
  633. // Check if this node has a handle registered.
  634. if n.handlers != nil {
  635. return ciPath
  636. }
  637. // No handle found.
  638. // Try to fix the path by adding a trailing slash
  639. if fixTrailingSlash {
  640. for i, c := range []byte(n.indices) {
  641. if c == '/' {
  642. n = n.children[i]
  643. if (len(n.path) == 1 && n.handlers != nil) ||
  644. (n.nType == catchAll && n.children[0].handlers != nil) {
  645. return append(ciPath, '/')
  646. }
  647. return nil
  648. }
  649. }
  650. }
  651. return nil
  652. }
  653. // If this node does not have a wildcard (param or catchAll) child,
  654. // we can just look up the next child node and continue to walk down
  655. // the tree
  656. if !n.wildChild {
  657. // Skip rune bytes already processed
  658. rb = shiftNRuneBytes(rb, npLen)
  659. if rb[0] != 0 {
  660. // Old rune not finished
  661. idxc := rb[0]
  662. for i, c := range []byte(n.indices) {
  663. if c == idxc {
  664. // continue with child node
  665. n = n.children[i]
  666. npLen = len(n.path)
  667. continue walk
  668. }
  669. }
  670. } else {
  671. // Process a new rune
  672. var rv rune
  673. // Find rune start.
  674. // Runes are up to 4 byte long,
  675. // -4 would definitely be another rune.
  676. var off int
  677. for max := min(npLen, 3); off < max; off++ {
  678. if i := npLen - off; utf8.RuneStart(oldPath[i]) {
  679. // read rune from cached path
  680. rv, _ = utf8.DecodeRuneInString(oldPath[i:])
  681. break
  682. }
  683. }
  684. // Calculate lowercase bytes of current rune
  685. lo := unicode.ToLower(rv)
  686. utf8.EncodeRune(rb[:], lo)
  687. // Skip already processed bytes
  688. rb = shiftNRuneBytes(rb, off)
  689. idxc := rb[0]
  690. for i, c := range []byte(n.indices) {
  691. // Lowercase matches
  692. if c == idxc {
  693. // must use a recursive approach since both the
  694. // uppercase byte and the lowercase byte might exist
  695. // as an index
  696. if out := n.children[i].findCaseInsensitivePathRec(
  697. path, ciPath, rb, fixTrailingSlash,
  698. ); out != nil {
  699. return out
  700. }
  701. break
  702. }
  703. }
  704. // If we found no match, the same for the uppercase rune,
  705. // if it differs
  706. if up := unicode.ToUpper(rv); up != lo {
  707. utf8.EncodeRune(rb[:], up)
  708. rb = shiftNRuneBytes(rb, off)
  709. idxc := rb[0]
  710. for i, c := range []byte(n.indices) {
  711. // Uppercase matches
  712. if c == idxc {
  713. // Continue with child node
  714. n = n.children[i]
  715. npLen = len(n.path)
  716. continue walk
  717. }
  718. }
  719. }
  720. }
  721. // Nothing found. We can recommend to redirect to the same URL
  722. // without a trailing slash if a leaf exists for that path
  723. if fixTrailingSlash && path == "/" && n.handlers != nil {
  724. return ciPath
  725. }
  726. return nil
  727. }
  728. n = n.children[0]
  729. switch n.nType {
  730. case param:
  731. // Find param end (either '/' or path end)
  732. end := 0
  733. for end < len(path) && path[end] != '/' {
  734. end++
  735. }
  736. // Add param value to case insensitive path
  737. ciPath = append(ciPath, path[:end]...)
  738. // We need to go deeper!
  739. if end < len(path) {
  740. if len(n.children) > 0 {
  741. // Continue with child node
  742. n = n.children[0]
  743. npLen = len(n.path)
  744. path = path[end:]
  745. continue
  746. }
  747. // ... but we can't
  748. if fixTrailingSlash && len(path) == end+1 {
  749. return ciPath
  750. }
  751. return nil
  752. }
  753. if n.handlers != nil {
  754. return ciPath
  755. }
  756. if fixTrailingSlash && len(n.children) == 1 {
  757. // No handle found. Check if a handle for this path + a
  758. // trailing slash exists
  759. n = n.children[0]
  760. if n.path == "/" && n.handlers != nil {
  761. return append(ciPath, '/')
  762. }
  763. }
  764. return nil
  765. case catchAll:
  766. return append(ciPath, path...)
  767. default:
  768. panic("invalid node type")
  769. }
  770. }
  771. // Nothing found.
  772. // Try to fix the path by adding / removing a trailing slash
  773. if fixTrailingSlash {
  774. if path == "/" {
  775. return ciPath
  776. }
  777. if len(path)+1 == npLen && n.path[len(path)] == '/' &&
  778. strings.EqualFold(path[1:], n.path[1:len(path)]) && n.handlers != nil {
  779. return append(ciPath, n.path...)
  780. }
  781. }
  782. return nil
  783. }