tree.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  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 := strings.SplitN(n.children[0].path, "/", 2)[0]
  306. panic("catch-all wildcard '" + path +
  307. "' in new path '" + fullPath +
  308. "' conflicts with existing path segment '" + pathSeg +
  309. "' in existing prefix '" + n.path + pathSeg +
  310. "'")
  311. }
  312. // currently fixed width 1 for '/'
  313. i--
  314. if path[i] != '/' {
  315. panic("no / before catch-all in path '" + fullPath + "'")
  316. }
  317. n.path = path[:i]
  318. // First node: catchAll node with empty path
  319. child := &node{
  320. wildChild: true,
  321. nType: catchAll,
  322. fullPath: fullPath,
  323. }
  324. n.addChild(child)
  325. n.indices = string('/')
  326. n = child
  327. n.priority++
  328. // second node: node holding the variable
  329. child = &node{
  330. path: path[i:],
  331. nType: catchAll,
  332. handlers: handlers,
  333. priority: 1,
  334. fullPath: fullPath,
  335. }
  336. n.children = []*node{child}
  337. return
  338. }
  339. // If no wildcard was found, simply insert the path and handle
  340. n.path = path
  341. n.handlers = handlers
  342. n.fullPath = fullPath
  343. }
  344. // nodeValue holds return values of (*Node).getValue method
  345. type nodeValue struct {
  346. handlers HandlersChain
  347. params *Params
  348. tsr bool
  349. fullPath string
  350. }
  351. type skippedNode struct {
  352. path string
  353. node *node
  354. paramsCount int16
  355. }
  356. // Returns the handle registered with the given path (key). The values of
  357. // wildcards are saved to a map.
  358. // If no handle can be found, a TSR (trailing slash redirect) recommendation is
  359. // made if a handle exists with an extra (without the) trailing slash for the
  360. // given path.
  361. func (n *node) getValue(path string, params *Params, skippedNodes *[]skippedNode, unescape bool) (value nodeValue) {
  362. var globalParamsCount int16
  363. walk: // Outer loop for walking the tree
  364. for {
  365. prefix := n.path
  366. if len(path) > len(prefix) {
  367. if path[:len(prefix)] == prefix {
  368. path = path[len(prefix):]
  369. // Try all the non-wildcard children first by matching the indices
  370. idxc := path[0]
  371. for i, c := range []byte(n.indices) {
  372. if c == idxc {
  373. // strings.HasPrefix(n.children[len(n.children)-1].path, ":") == n.wildChild
  374. if n.wildChild {
  375. index := len(*skippedNodes)
  376. *skippedNodes = (*skippedNodes)[:index+1]
  377. (*skippedNodes)[index] = skippedNode{
  378. path: prefix + path,
  379. node: &node{
  380. path: n.path,
  381. wildChild: n.wildChild,
  382. nType: n.nType,
  383. priority: n.priority,
  384. children: n.children,
  385. handlers: n.handlers,
  386. fullPath: n.fullPath,
  387. },
  388. paramsCount: globalParamsCount,
  389. }
  390. }
  391. n = n.children[i]
  392. continue walk
  393. }
  394. }
  395. if !n.wildChild {
  396. // If the path at the end of the loop is not equal to '/' and the current node has no child nodes
  397. // the current node needs to roll back to last valid skippedNode
  398. if path != "/" {
  399. for length := len(*skippedNodes); length > 0; length-- {
  400. skippedNode := (*skippedNodes)[length-1]
  401. *skippedNodes = (*skippedNodes)[:length-1]
  402. if strings.HasSuffix(skippedNode.path, path) {
  403. path = skippedNode.path
  404. n = skippedNode.node
  405. if value.params != nil {
  406. *value.params = (*value.params)[:skippedNode.paramsCount]
  407. }
  408. globalParamsCount = skippedNode.paramsCount
  409. continue walk
  410. }
  411. }
  412. }
  413. // Nothing found.
  414. // We can recommend to redirect to the same URL without a
  415. // trailing slash if a leaf exists for that path.
  416. value.tsr = path == "/" && n.handlers != nil
  417. return
  418. }
  419. // Handle wildcard child, which is always at the end of the array
  420. n = n.children[len(n.children)-1]
  421. globalParamsCount++
  422. switch n.nType {
  423. case param:
  424. // fix truncate the parameter
  425. // tree_test.go line: 204
  426. // Find param end (either '/' or path end)
  427. end := 0
  428. for end < len(path) && path[end] != '/' {
  429. end++
  430. }
  431. // Save param value
  432. if params != nil && cap(*params) > 0 {
  433. if value.params == nil {
  434. value.params = params
  435. }
  436. // Expand slice within preallocated capacity
  437. i := len(*value.params)
  438. *value.params = (*value.params)[:i+1]
  439. val := path[:end]
  440. if unescape {
  441. if v, err := url.QueryUnescape(val); err == nil {
  442. val = v
  443. }
  444. }
  445. (*value.params)[i] = Param{
  446. Key: n.path[1:],
  447. Value: val,
  448. }
  449. }
  450. // we need to go deeper!
  451. if end < len(path) {
  452. if len(n.children) > 0 {
  453. path = path[end:]
  454. n = n.children[0]
  455. continue walk
  456. }
  457. // ... but we can't
  458. value.tsr = len(path) == end+1
  459. return
  460. }
  461. if value.handlers = n.handlers; value.handlers != nil {
  462. value.fullPath = n.fullPath
  463. return
  464. }
  465. if len(n.children) == 1 {
  466. // No handle found. Check if a handle for this path + a
  467. // trailing slash exists for TSR recommendation
  468. n = n.children[0]
  469. value.tsr = (n.path == "/" && n.handlers != nil) || (n.path == "" && n.indices == "/")
  470. }
  471. return
  472. case catchAll:
  473. // Save param value
  474. if params != nil {
  475. if value.params == nil {
  476. value.params = params
  477. }
  478. // Expand slice within preallocated capacity
  479. i := len(*value.params)
  480. *value.params = (*value.params)[:i+1]
  481. val := path
  482. if unescape {
  483. if v, err := url.QueryUnescape(path); err == nil {
  484. val = v
  485. }
  486. }
  487. (*value.params)[i] = Param{
  488. Key: n.path[2:],
  489. Value: val,
  490. }
  491. }
  492. value.handlers = n.handlers
  493. value.fullPath = n.fullPath
  494. return
  495. default:
  496. panic("invalid node type")
  497. }
  498. }
  499. }
  500. if path == prefix {
  501. // 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
  502. // the current node needs to roll back to last valid skippedNode
  503. if n.handlers == nil && path != "/" {
  504. for length := len(*skippedNodes); length > 0; length-- {
  505. skippedNode := (*skippedNodes)[length-1]
  506. *skippedNodes = (*skippedNodes)[:length-1]
  507. if strings.HasSuffix(skippedNode.path, path) {
  508. path = skippedNode.path
  509. n = skippedNode.node
  510. if value.params != nil {
  511. *value.params = (*value.params)[:skippedNode.paramsCount]
  512. }
  513. globalParamsCount = skippedNode.paramsCount
  514. continue walk
  515. }
  516. }
  517. // n = latestNode.children[len(latestNode.children)-1]
  518. }
  519. // We should have reached the node containing the handle.
  520. // Check if this node has a handle registered.
  521. if value.handlers = n.handlers; value.handlers != nil {
  522. value.fullPath = n.fullPath
  523. return
  524. }
  525. // If there is no handle for this route, but this route has a
  526. // wildcard child, there must be a handle for this path with an
  527. // additional trailing slash
  528. if path == "/" && n.wildChild && n.nType != root {
  529. value.tsr = true
  530. return
  531. }
  532. if path == "/" && n.nType == static {
  533. value.tsr = true
  534. return
  535. }
  536. // No handle found. Check if a handle for this path + a
  537. // trailing slash exists for trailing slash recommendation
  538. for i, c := range []byte(n.indices) {
  539. if c == '/' {
  540. n = n.children[i]
  541. value.tsr = (len(n.path) == 1 && n.handlers != nil) ||
  542. (n.nType == catchAll && n.children[0].handlers != nil)
  543. return
  544. }
  545. }
  546. return
  547. }
  548. // Nothing found. We can recommend to redirect to the same URL with an
  549. // extra trailing slash if a leaf exists for that path
  550. value.tsr = path == "/" ||
  551. (len(prefix) == len(path)+1 && prefix[len(path)] == '/' &&
  552. path == prefix[:len(prefix)-1] && n.handlers != nil)
  553. // roll back to last valid skippedNode
  554. if !value.tsr && path != "/" {
  555. for length := len(*skippedNodes); length > 0; length-- {
  556. skippedNode := (*skippedNodes)[length-1]
  557. *skippedNodes = (*skippedNodes)[:length-1]
  558. if strings.HasSuffix(skippedNode.path, path) {
  559. path = skippedNode.path
  560. n = skippedNode.node
  561. if value.params != nil {
  562. *value.params = (*value.params)[:skippedNode.paramsCount]
  563. }
  564. globalParamsCount = skippedNode.paramsCount
  565. continue walk
  566. }
  567. }
  568. }
  569. return
  570. }
  571. }
  572. // Makes a case-insensitive lookup of the given path and tries to find a handler.
  573. // It can optionally also fix trailing slashes.
  574. // It returns the case-corrected path and a bool indicating whether the lookup
  575. // was successful.
  576. func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) ([]byte, bool) {
  577. const stackBufSize = 128
  578. // Use a static sized buffer on the stack in the common case.
  579. // If the path is too long, allocate a buffer on the heap instead.
  580. buf := make([]byte, 0, stackBufSize)
  581. if length := len(path) + 1; length > stackBufSize {
  582. buf = make([]byte, 0, length)
  583. }
  584. ciPath := n.findCaseInsensitivePathRec(
  585. path,
  586. buf, // Preallocate enough memory for new path
  587. [4]byte{}, // Empty rune buffer
  588. fixTrailingSlash,
  589. )
  590. return ciPath, ciPath != nil
  591. }
  592. // Shift bytes in array by n bytes left
  593. func shiftNRuneBytes(rb [4]byte, n int) [4]byte {
  594. switch n {
  595. case 0:
  596. return rb
  597. case 1:
  598. return [4]byte{rb[1], rb[2], rb[3], 0}
  599. case 2:
  600. return [4]byte{rb[2], rb[3]}
  601. case 3:
  602. return [4]byte{rb[3]}
  603. default:
  604. return [4]byte{}
  605. }
  606. }
  607. // Recursive case-insensitive lookup function used by n.findCaseInsensitivePath
  608. func (n *node) findCaseInsensitivePathRec(path string, ciPath []byte, rb [4]byte, fixTrailingSlash bool) []byte {
  609. npLen := len(n.path)
  610. walk: // Outer loop for walking the tree
  611. for len(path) >= npLen && (npLen == 0 || strings.EqualFold(path[1:npLen], n.path[1:])) {
  612. // Add common prefix to result
  613. oldPath := path
  614. path = path[npLen:]
  615. ciPath = append(ciPath, n.path...)
  616. if len(path) == 0 {
  617. // We should have reached the node containing the handle.
  618. // Check if this node has a handle registered.
  619. if n.handlers != nil {
  620. return ciPath
  621. }
  622. // No handle found.
  623. // Try to fix the path by adding a trailing slash
  624. if fixTrailingSlash {
  625. for i, c := range []byte(n.indices) {
  626. if c == '/' {
  627. n = n.children[i]
  628. if (len(n.path) == 1 && n.handlers != nil) ||
  629. (n.nType == catchAll && n.children[0].handlers != nil) {
  630. return append(ciPath, '/')
  631. }
  632. return nil
  633. }
  634. }
  635. }
  636. return nil
  637. }
  638. // If this node does not have a wildcard (param or catchAll) child,
  639. // we can just look up the next child node and continue to walk down
  640. // the tree
  641. if !n.wildChild {
  642. // Skip rune bytes already processed
  643. rb = shiftNRuneBytes(rb, npLen)
  644. if rb[0] != 0 {
  645. // Old rune not finished
  646. idxc := rb[0]
  647. for i, c := range []byte(n.indices) {
  648. if c == idxc {
  649. // continue with child node
  650. n = n.children[i]
  651. npLen = len(n.path)
  652. continue walk
  653. }
  654. }
  655. } else {
  656. // Process a new rune
  657. var rv rune
  658. // Find rune start.
  659. // Runes are up to 4 byte long,
  660. // -4 would definitely be another rune.
  661. var off int
  662. for max := min(npLen, 3); off < max; off++ {
  663. if i := npLen - off; utf8.RuneStart(oldPath[i]) {
  664. // read rune from cached path
  665. rv, _ = utf8.DecodeRuneInString(oldPath[i:])
  666. break
  667. }
  668. }
  669. // Calculate lowercase bytes of current rune
  670. lo := unicode.ToLower(rv)
  671. utf8.EncodeRune(rb[:], lo)
  672. // Skip already processed bytes
  673. rb = shiftNRuneBytes(rb, off)
  674. idxc := rb[0]
  675. for i, c := range []byte(n.indices) {
  676. // Lowercase matches
  677. if c == idxc {
  678. // must use a recursive approach since both the
  679. // uppercase byte and the lowercase byte might exist
  680. // as an index
  681. if out := n.children[i].findCaseInsensitivePathRec(
  682. path, ciPath, rb, fixTrailingSlash,
  683. ); out != nil {
  684. return out
  685. }
  686. break
  687. }
  688. }
  689. // If we found no match, the same for the uppercase rune,
  690. // if it differs
  691. if up := unicode.ToUpper(rv); up != lo {
  692. utf8.EncodeRune(rb[:], up)
  693. rb = shiftNRuneBytes(rb, off)
  694. idxc := rb[0]
  695. for i, c := range []byte(n.indices) {
  696. // Uppercase matches
  697. if c == idxc {
  698. // Continue with child node
  699. n = n.children[i]
  700. npLen = len(n.path)
  701. continue walk
  702. }
  703. }
  704. }
  705. }
  706. // Nothing found. We can recommend to redirect to the same URL
  707. // without a trailing slash if a leaf exists for that path
  708. if fixTrailingSlash && path == "/" && n.handlers != nil {
  709. return ciPath
  710. }
  711. return nil
  712. }
  713. n = n.children[0]
  714. switch n.nType {
  715. case param:
  716. // Find param end (either '/' or path end)
  717. end := 0
  718. for end < len(path) && path[end] != '/' {
  719. end++
  720. }
  721. // Add param value to case insensitive path
  722. ciPath = append(ciPath, path[:end]...)
  723. // We need to go deeper!
  724. if end < len(path) {
  725. if len(n.children) > 0 {
  726. // Continue with child node
  727. n = n.children[0]
  728. npLen = len(n.path)
  729. path = path[end:]
  730. continue
  731. }
  732. // ... but we can't
  733. if fixTrailingSlash && len(path) == end+1 {
  734. return ciPath
  735. }
  736. return nil
  737. }
  738. if n.handlers != nil {
  739. return ciPath
  740. }
  741. if fixTrailingSlash && len(n.children) == 1 {
  742. // No handle found. Check if a handle for this path + a
  743. // trailing slash exists
  744. n = n.children[0]
  745. if n.path == "/" && n.handlers != nil {
  746. return append(ciPath, '/')
  747. }
  748. }
  749. return nil
  750. case catchAll:
  751. return append(ciPath, path...)
  752. default:
  753. panic("invalid node type")
  754. }
  755. }
  756. // Nothing found.
  757. // Try to fix the path by adding / removing a trailing slash
  758. if fixTrailingSlash {
  759. if path == "/" {
  760. return ciPath
  761. }
  762. if len(path)+1 == npLen && n.path[len(path)] == '/' &&
  763. strings.EqualFold(path[1:], n.path[1:len(path)]) && n.handlers != nil {
  764. return append(ciPath, n.path...)
  765. }
  766. }
  767. return nil
  768. }