tree.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  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. "net/url"
  7. "strings"
  8. "unicode"
  9. )
  10. // Param is a single URL parameter, consisting of a key and a value.
  11. type Param struct {
  12. Key string
  13. Value string
  14. }
  15. // Params is a Param-slice, as returned by the router.
  16. // The slice is ordered, the first URL parameter is also the first slice value.
  17. // It is therefore safe to read values by the index.
  18. type Params []Param
  19. // Get returns the value of the first Param which key matches the given name.
  20. // If no matching Param is found, an empty string is returned.
  21. func (ps Params) Get(name string) (string, bool) {
  22. for _, entry := range ps {
  23. if entry.Key == name {
  24. return entry.Value, true
  25. }
  26. }
  27. return "", false
  28. }
  29. // ByName returns the value of the first Param which key matches the given name.
  30. // If no matching Param is found, an empty string is returned.
  31. func (ps Params) ByName(name string) (va string) {
  32. va, _ = ps.Get(name)
  33. return
  34. }
  35. type methodTree struct {
  36. method string
  37. root *node
  38. }
  39. type methodTrees []methodTree
  40. func (trees methodTrees) get(method string) *node {
  41. for _, tree := range trees {
  42. if tree.method == method {
  43. return tree.root
  44. }
  45. }
  46. return nil
  47. }
  48. func min(a, b int) int {
  49. if a <= b {
  50. return a
  51. }
  52. return b
  53. }
  54. func countParams(path string) uint8 {
  55. var n uint
  56. for i := 0; i < len(path); i++ {
  57. if path[i] == ':' || path[i] == '*' {
  58. n++
  59. }
  60. }
  61. if n >= 255 {
  62. return 255
  63. }
  64. return uint8(n)
  65. }
  66. type nodeType uint8
  67. const (
  68. static nodeType = iota // default
  69. root
  70. param
  71. catchAll
  72. )
  73. type node struct {
  74. path string
  75. indices string
  76. children []*node
  77. handlers HandlersChain
  78. priority uint32
  79. nType nodeType
  80. maxParams uint8
  81. wildChild bool
  82. fullPath string
  83. }
  84. // increments priority of the given child and reorders if necessary.
  85. func (n *node) incrementChildPrio(pos int) int {
  86. n.children[pos].priority++
  87. prio := n.children[pos].priority
  88. // adjust position (move to front)
  89. newPos := pos
  90. for newPos > 0 && n.children[newPos-1].priority < prio {
  91. // swap node positions
  92. n.children[newPos-1], n.children[newPos] = n.children[newPos], n.children[newPos-1]
  93. newPos--
  94. }
  95. // build new index char string
  96. if newPos != pos {
  97. n.indices = n.indices[:newPos] + // unchanged prefix, might be empty
  98. n.indices[pos:pos+1] + // the index char we move
  99. n.indices[newPos:pos] + n.indices[pos+1:] // rest without char at 'pos'
  100. }
  101. return newPos
  102. }
  103. // addRoute adds a node with the given handle to the path.
  104. // Not concurrency-safe!
  105. func (n *node) addRoute(path string, handlers HandlersChain) {
  106. fullPath := path
  107. n.priority++
  108. numParams := countParams(path)
  109. parentFullPathIndex := 0
  110. // non-empty tree
  111. if len(n.path) > 0 || len(n.children) > 0 {
  112. walk:
  113. for {
  114. // Update maxParams of the current node
  115. if numParams > n.maxParams {
  116. n.maxParams = numParams
  117. }
  118. // Find the longest common prefix.
  119. // This also implies that the common prefix contains no ':' or '*'
  120. // since the existing key can't contain those chars.
  121. i := 0
  122. max := min(len(path), len(n.path))
  123. for i < max && path[i] == n.path[i] {
  124. i++
  125. }
  126. // Split edge
  127. if i < len(n.path) {
  128. child := node{
  129. path: n.path[i:],
  130. wildChild: n.wildChild,
  131. indices: n.indices,
  132. children: n.children,
  133. handlers: n.handlers,
  134. priority: n.priority - 1,
  135. fullPath: n.fullPath,
  136. }
  137. // Update maxParams (max of all children)
  138. for i := range child.children {
  139. if child.children[i].maxParams > child.maxParams {
  140. child.maxParams = child.children[i].maxParams
  141. }
  142. }
  143. n.children = []*node{&child}
  144. // []byte for proper unicode char conversion, see #65
  145. n.indices = string([]byte{n.path[i]})
  146. n.path = path[:i]
  147. n.handlers = nil
  148. n.wildChild = false
  149. n.fullPath = fullPath[:parentFullPathIndex+i]
  150. }
  151. // Make new node a child of this node
  152. if i < len(path) {
  153. path = path[i:]
  154. if n.wildChild {
  155. parentFullPathIndex += len(n.path)
  156. n = n.children[0]
  157. n.priority++
  158. // Update maxParams of the child node
  159. if numParams > n.maxParams {
  160. n.maxParams = numParams
  161. }
  162. numParams--
  163. // Check if the wildcard matches
  164. if len(path) >= len(n.path) && n.path == path[:len(n.path)] {
  165. // check for longer wildcard, e.g. :name and :names
  166. if len(n.path) >= len(path) || path[len(n.path)] == '/' {
  167. continue walk
  168. }
  169. }
  170. pathSeg := path
  171. if n.nType != catchAll {
  172. pathSeg = strings.SplitN(path, "/", 2)[0]
  173. }
  174. prefix := fullPath[:strings.Index(fullPath, pathSeg)] + n.path
  175. panic("'" + pathSeg +
  176. "' in new path '" + fullPath +
  177. "' conflicts with existing wildcard '" + n.path +
  178. "' in existing prefix '" + prefix +
  179. "'")
  180. }
  181. c := path[0]
  182. // slash after param
  183. if n.nType == param && c == '/' && len(n.children) == 1 {
  184. parentFullPathIndex += len(n.path)
  185. n = n.children[0]
  186. n.priority++
  187. continue walk
  188. }
  189. // Check if a child with the next path byte exists
  190. for i := 0; i < len(n.indices); i++ {
  191. if c == n.indices[i] {
  192. parentFullPathIndex += len(n.path)
  193. i = n.incrementChildPrio(i)
  194. n = n.children[i]
  195. continue walk
  196. }
  197. }
  198. // Otherwise insert it
  199. if c != ':' && c != '*' {
  200. // []byte for proper unicode char conversion, see #65
  201. n.indices += string([]byte{c})
  202. child := &node{
  203. maxParams: numParams,
  204. fullPath: fullPath,
  205. }
  206. n.children = append(n.children, child)
  207. n.incrementChildPrio(len(n.indices) - 1)
  208. n = child
  209. }
  210. n.insertChild(numParams, path, fullPath, handlers)
  211. return
  212. } else if i == len(path) { // Make node a (in-path) leaf
  213. if n.handlers != nil {
  214. panic("handlers are already registered for path '" + fullPath + "'")
  215. }
  216. n.handlers = handlers
  217. }
  218. return
  219. }
  220. } else { // Empty tree
  221. n.insertChild(numParams, path, fullPath, handlers)
  222. n.nType = root
  223. }
  224. }
  225. func (n *node) insertChild(numParams uint8, path string, fullPath string, handlers HandlersChain) {
  226. var offset int // already handled bytes of the path
  227. // find prefix until first wildcard (beginning with ':' or '*')
  228. for i, max := 0, len(path); numParams > 0; i++ {
  229. c := path[i]
  230. if c != ':' && c != '*' {
  231. continue
  232. }
  233. // find wildcard end (either '/' or path end)
  234. end := i + 1
  235. for end < max && path[end] != '/' {
  236. switch path[end] {
  237. // the wildcard name must not contain ':' and '*'
  238. case ':', '*':
  239. panic("only one wildcard per path segment is allowed, has: '" +
  240. path[i:] + "' in path '" + fullPath + "'")
  241. default:
  242. end++
  243. }
  244. }
  245. // check if this Node existing children which would be
  246. // unreachable if we insert the wildcard here
  247. if len(n.children) > 0 {
  248. panic("wildcard route '" + path[i:end] +
  249. "' conflicts with existing children in path '" + fullPath + "'")
  250. }
  251. // check if the wildcard has a name
  252. if end-i < 2 {
  253. panic("wildcards must be named with a non-empty name in path '" + fullPath + "'")
  254. }
  255. if c == ':' { // param
  256. // split path at the beginning of the wildcard
  257. if i > 0 {
  258. n.path = path[offset:i]
  259. offset = i
  260. }
  261. child := &node{
  262. nType: param,
  263. maxParams: numParams,
  264. fullPath: fullPath,
  265. }
  266. n.children = []*node{child}
  267. n.wildChild = true
  268. n = child
  269. n.priority++
  270. numParams--
  271. // if the path doesn't end with the wildcard, then there
  272. // will be another non-wildcard subpath starting with '/'
  273. if end < max {
  274. n.path = path[offset:end]
  275. offset = end
  276. child := &node{
  277. maxParams: numParams,
  278. priority: 1,
  279. fullPath: fullPath,
  280. }
  281. n.children = []*node{child}
  282. n = child
  283. }
  284. } else { // catchAll
  285. if end != max || numParams > 1 {
  286. panic("catch-all routes are only allowed at the end of the path in path '" + fullPath + "'")
  287. }
  288. if len(n.path) > 0 && n.path[len(n.path)-1] == '/' {
  289. panic("catch-all conflicts with existing handle for the path segment root in path '" + fullPath + "'")
  290. }
  291. // currently fixed width 1 for '/'
  292. i--
  293. if path[i] != '/' {
  294. panic("no / before catch-all in path '" + fullPath + "'")
  295. }
  296. n.path = path[offset:i]
  297. // first node: catchAll node with empty path
  298. child := &node{
  299. wildChild: true,
  300. nType: catchAll,
  301. maxParams: 1,
  302. fullPath: fullPath,
  303. }
  304. n.children = []*node{child}
  305. n.indices = string(path[i])
  306. n = child
  307. n.priority++
  308. // second node: node holding the variable
  309. child = &node{
  310. path: path[i:],
  311. nType: catchAll,
  312. maxParams: 1,
  313. handlers: handlers,
  314. priority: 1,
  315. fullPath: fullPath,
  316. }
  317. n.children = []*node{child}
  318. return
  319. }
  320. }
  321. // insert remaining path part and handle to the leaf
  322. n.path = path[offset:]
  323. n.handlers = handlers
  324. n.fullPath = fullPath
  325. }
  326. // nodeValue holds return values of (*Node).getValue method
  327. type nodeValue struct {
  328. handlers HandlersChain
  329. params Params
  330. tsr bool
  331. fullPath string
  332. }
  333. // getValue returns the handle registered with the given path (key). The values of
  334. // wildcards are saved to a map.
  335. // If no handle can be found, a TSR (trailing slash redirect) recommendation is
  336. // made if a handle exists with an extra (without the) trailing slash for the
  337. // given path.
  338. func (n *node) getValue(path string, po Params, unescape bool) (value nodeValue) {
  339. value.params = po
  340. walk: // Outer loop for walking the tree
  341. for {
  342. if len(path) > len(n.path) {
  343. if path[:len(n.path)] == n.path {
  344. path = path[len(n.path):]
  345. // If this node does not have a wildcard (param or catchAll)
  346. // child, we can just look up the next child node and continue
  347. // to walk down the tree
  348. if !n.wildChild {
  349. c := path[0]
  350. for i := 0; i < len(n.indices); i++ {
  351. if c == n.indices[i] {
  352. n = n.children[i]
  353. continue walk
  354. }
  355. }
  356. // Nothing found.
  357. // We can recommend to redirect to the same URL without a
  358. // trailing slash if a leaf exists for that path.
  359. value.tsr = path == "/" && n.handlers != nil
  360. return
  361. }
  362. // handle wildcard child
  363. n = n.children[0]
  364. switch n.nType {
  365. case param:
  366. // find param end (either '/' or path end)
  367. end := 0
  368. for end < len(path) && path[end] != '/' {
  369. end++
  370. }
  371. // save param value
  372. if cap(value.params) < int(n.maxParams) {
  373. value.params = make(Params, 0, n.maxParams)
  374. }
  375. i := len(value.params)
  376. value.params = value.params[:i+1] // expand slice within preallocated capacity
  377. value.params[i].Key = n.path[1:]
  378. val := path[:end]
  379. if unescape {
  380. var err error
  381. if value.params[i].Value, err = url.QueryUnescape(val); err != nil {
  382. value.params[i].Value = val // fallback, in case of error
  383. }
  384. } else {
  385. value.params[i].Value = val
  386. }
  387. // we need to go deeper!
  388. if end < len(path) {
  389. if len(n.children) > 0 {
  390. path = path[end:]
  391. n = n.children[0]
  392. continue walk
  393. }
  394. // ... but we can't
  395. value.tsr = len(path) == end+1
  396. return
  397. }
  398. if value.handlers = n.handlers; value.handlers != nil {
  399. value.fullPath = n.fullPath
  400. return
  401. }
  402. if len(n.children) == 1 {
  403. // No handle found. Check if a handle for this path + a
  404. // trailing slash exists for TSR recommendation
  405. n = n.children[0]
  406. value.tsr = n.path == "/" && n.handlers != nil
  407. }
  408. return
  409. case catchAll:
  410. // save param value
  411. if cap(value.params) < int(n.maxParams) {
  412. value.params = make(Params, 0, n.maxParams)
  413. }
  414. i := len(value.params)
  415. value.params = value.params[:i+1] // expand slice within preallocated capacity
  416. value.params[i].Key = n.path[2:]
  417. if unescape {
  418. var err error
  419. if value.params[i].Value, err = url.QueryUnescape(path); err != nil {
  420. value.params[i].Value = path // fallback, in case of error
  421. }
  422. } else {
  423. value.params[i].Value = path
  424. }
  425. value.handlers = n.handlers
  426. value.fullPath = n.fullPath
  427. return
  428. default:
  429. panic("invalid node type")
  430. }
  431. }
  432. } else if path == n.path {
  433. // We should have reached the node containing the handle.
  434. // Check if this node has a handle registered.
  435. if value.handlers = n.handlers; value.handlers != nil {
  436. value.fullPath = n.fullPath
  437. return
  438. }
  439. if path == "/" && n.wildChild && n.nType != root {
  440. value.tsr = true
  441. return
  442. }
  443. // No handle found. Check if a handle for this path + a
  444. // trailing slash exists for trailing slash recommendation
  445. for i := 0; i < len(n.indices); i++ {
  446. if n.indices[i] == '/' {
  447. n = n.children[i]
  448. value.tsr = (len(n.path) == 1 && n.handlers != nil) ||
  449. (n.nType == catchAll && n.children[0].handlers != nil)
  450. return
  451. }
  452. }
  453. return
  454. }
  455. // Nothing found. We can recommend to redirect to the same URL with an
  456. // extra trailing slash if a leaf exists for that path
  457. value.tsr = (path == "/") ||
  458. (len(n.path) == len(path)+1 && n.path[len(path)] == '/' &&
  459. path == n.path[:len(n.path)-1] && n.handlers != nil)
  460. return
  461. }
  462. }
  463. // findCaseInsensitivePath makes a case-insensitive lookup of the given path and tries to find a handler.
  464. // It can optionally also fix trailing slashes.
  465. // It returns the case-corrected path and a bool indicating whether the lookup
  466. // was successful.
  467. func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) (ciPath []byte, found bool) {
  468. ciPath = make([]byte, 0, len(path)+1) // preallocate enough memory
  469. // Outer loop for walking the tree
  470. for len(path) >= len(n.path) && strings.EqualFold(path[:len(n.path)], n.path) {
  471. path = path[len(n.path):]
  472. ciPath = append(ciPath, n.path...)
  473. if len(path) > 0 {
  474. // If this node does not have a wildcard (param or catchAll) child,
  475. // we can just look up the next child node and continue to walk down
  476. // the tree
  477. if !n.wildChild {
  478. r := unicode.ToLower(rune(path[0]))
  479. for i, index := range n.indices {
  480. // must use recursive approach since both index and
  481. // ToLower(index) could exist. We must check both.
  482. if r == unicode.ToLower(index) {
  483. out, found := n.children[i].findCaseInsensitivePath(path, fixTrailingSlash)
  484. if found {
  485. return append(ciPath, out...), true
  486. }
  487. }
  488. }
  489. // Nothing found. We can recommend to redirect to the same URL
  490. // without a trailing slash if a leaf exists for that path
  491. found = fixTrailingSlash && path == "/" && n.handlers != nil
  492. return
  493. }
  494. n = n.children[0]
  495. switch n.nType {
  496. case param:
  497. // find param end (either '/' or path end)
  498. k := 0
  499. for k < len(path) && path[k] != '/' {
  500. k++
  501. }
  502. // add param value to case insensitive path
  503. ciPath = append(ciPath, path[:k]...)
  504. // we need to go deeper!
  505. if k < len(path) {
  506. if len(n.children) > 0 {
  507. path = path[k:]
  508. n = n.children[0]
  509. continue
  510. }
  511. // ... but we can't
  512. if fixTrailingSlash && len(path) == k+1 {
  513. return ciPath, true
  514. }
  515. return
  516. }
  517. if n.handlers != nil {
  518. return ciPath, true
  519. } else if fixTrailingSlash && len(n.children) == 1 {
  520. // No handle found. Check if a handle for this path + a
  521. // trailing slash exists
  522. n = n.children[0]
  523. if n.path == "/" && n.handlers != nil {
  524. return append(ciPath, '/'), true
  525. }
  526. }
  527. return
  528. case catchAll:
  529. return append(ciPath, path...), true
  530. default:
  531. panic("invalid node type")
  532. }
  533. } else {
  534. // We should have reached the node containing the handle.
  535. // Check if this node has a handle registered.
  536. if n.handlers != nil {
  537. return ciPath, true
  538. }
  539. // No handle found.
  540. // Try to fix the path by adding a trailing slash
  541. if fixTrailingSlash {
  542. for i := 0; i < len(n.indices); i++ {
  543. if n.indices[i] == '/' {
  544. n = n.children[i]
  545. if (len(n.path) == 1 && n.handlers != nil) ||
  546. (n.nType == catchAll && n.children[0].handlers != nil) {
  547. return append(ciPath, '/'), true
  548. }
  549. return
  550. }
  551. }
  552. }
  553. return
  554. }
  555. }
  556. // Nothing found.
  557. // Try to fix the path by adding / removing a trailing slash
  558. if fixTrailingSlash {
  559. if path == "/" {
  560. return ciPath, true
  561. }
  562. if len(path)+1 == len(n.path) && n.path[len(path)] == '/' &&
  563. strings.EqualFold(path, n.path[:len(path)]) &&
  564. n.handlers != nil {
  565. return append(ciPath, n.path...), true
  566. }
  567. }
  568. return
  569. }