tree.go 15 KB

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