tree.go 15 KB

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