tree.go 14 KB

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