tree.go 16 KB

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