tree.go 16 KB

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