tree.go 15 KB

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