tree.go 15 KB

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