tree.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  1. package chi
  2. // Radix tree implementation below is a based on the original work by
  3. // Armon Dadgar in https://github.com/armon/go-radix/blob/master/radix.go
  4. // (MIT licensed). It's been heavily modified for use as a HTTP routing tree.
  5. import (
  6. "fmt"
  7. "net/http"
  8. "regexp"
  9. "sort"
  10. "strconv"
  11. "strings"
  12. )
  13. type methodTyp uint
  14. const (
  15. mSTUB methodTyp = 1 << iota
  16. mCONNECT
  17. mDELETE
  18. mGET
  19. mHEAD
  20. mOPTIONS
  21. mPATCH
  22. mPOST
  23. mPUT
  24. mTRACE
  25. )
  26. var mALL = mCONNECT | mDELETE | mGET | mHEAD |
  27. mOPTIONS | mPATCH | mPOST | mPUT | mTRACE
  28. var methodMap = map[string]methodTyp{
  29. http.MethodConnect: mCONNECT,
  30. http.MethodDelete: mDELETE,
  31. http.MethodGet: mGET,
  32. http.MethodHead: mHEAD,
  33. http.MethodOptions: mOPTIONS,
  34. http.MethodPatch: mPATCH,
  35. http.MethodPost: mPOST,
  36. http.MethodPut: mPUT,
  37. http.MethodTrace: mTRACE,
  38. }
  39. var reverseMethodMap = map[methodTyp]string{
  40. mCONNECT: http.MethodConnect,
  41. mDELETE: http.MethodDelete,
  42. mGET: http.MethodGet,
  43. mHEAD: http.MethodHead,
  44. mOPTIONS: http.MethodOptions,
  45. mPATCH: http.MethodPatch,
  46. mPOST: http.MethodPost,
  47. mPUT: http.MethodPut,
  48. mTRACE: http.MethodTrace,
  49. }
  50. // RegisterMethod adds support for custom HTTP method handlers, available
  51. // via Router#Method and Router#MethodFunc
  52. func RegisterMethod(method string) {
  53. if method == "" {
  54. return
  55. }
  56. method = strings.ToUpper(method)
  57. if _, ok := methodMap[method]; ok {
  58. return
  59. }
  60. n := len(methodMap)
  61. if n > strconv.IntSize-2 {
  62. panic(fmt.Sprintf("chi: max number of methods reached (%d)", strconv.IntSize))
  63. }
  64. mt := methodTyp(2 << n)
  65. methodMap[method] = mt
  66. reverseMethodMap[mt] = method
  67. mALL |= mt
  68. }
  69. type nodeTyp uint8
  70. const (
  71. ntStatic nodeTyp = iota // /home
  72. ntRegexp // /{id:[0-9]+}
  73. ntParam // /{user}
  74. ntCatchAll // /api/v1/*
  75. )
  76. type node struct {
  77. // subroutes on the leaf node
  78. subroutes Routes
  79. // regexp matcher for regexp nodes
  80. rex *regexp.Regexp
  81. // HTTP handler endpoints on the leaf node
  82. endpoints endpoints
  83. // prefix is the common prefix we ignore
  84. prefix string
  85. // child nodes should be stored in-order for iteration,
  86. // in groups of the node type.
  87. children [ntCatchAll + 1]nodes
  88. // first byte of the child prefix
  89. tail byte
  90. // node type: static, regexp, param, catchAll
  91. typ nodeTyp
  92. // first byte of the prefix
  93. label byte
  94. }
  95. // endpoints is a mapping of http method constants to handlers
  96. // for a given route.
  97. type endpoints map[methodTyp]*endpoint
  98. type endpoint struct {
  99. // endpoint handler
  100. handler http.Handler
  101. // pattern is the routing pattern for handler nodes
  102. pattern string
  103. // parameter keys recorded on handler nodes
  104. paramKeys []string
  105. }
  106. func (s endpoints) Value(method methodTyp) *endpoint {
  107. mh, ok := s[method]
  108. if !ok {
  109. mh = &endpoint{}
  110. s[method] = mh
  111. }
  112. return mh
  113. }
  114. func (n *node) InsertRoute(method methodTyp, pattern string, handler http.Handler) *node {
  115. var parent *node
  116. search := pattern
  117. for {
  118. // Handle key exhaustion
  119. if len(search) == 0 {
  120. // Insert or update the node's leaf handler
  121. n.setEndpoint(method, handler, pattern)
  122. return n
  123. }
  124. // We're going to be searching for a wild node next,
  125. // in this case, we need to get the tail
  126. var label = search[0]
  127. var segTail byte
  128. var segEndIdx int
  129. var segTyp nodeTyp
  130. var segRexpat string
  131. if label == '{' || label == '*' {
  132. segTyp, _, segRexpat, segTail, _, segEndIdx = patNextSegment(search)
  133. }
  134. var prefix string
  135. if segTyp == ntRegexp {
  136. prefix = segRexpat
  137. }
  138. // Look for the edge to attach to
  139. parent = n
  140. n = n.getEdge(segTyp, label, segTail, prefix)
  141. // No edge, create one
  142. if n == nil {
  143. child := &node{label: label, tail: segTail, prefix: search}
  144. hn := parent.addChild(child, search)
  145. hn.setEndpoint(method, handler, pattern)
  146. return hn
  147. }
  148. // Found an edge to match the pattern
  149. if n.typ > ntStatic {
  150. // We found a param node, trim the param from the search path and continue.
  151. // This param/wild pattern segment would already be on the tree from a previous
  152. // call to addChild when creating a new node.
  153. search = search[segEndIdx:]
  154. continue
  155. }
  156. // Static nodes fall below here.
  157. // Determine longest prefix of the search key on match.
  158. commonPrefix := longestPrefix(search, n.prefix)
  159. if commonPrefix == len(n.prefix) {
  160. // the common prefix is as long as the current node's prefix we're attempting to insert.
  161. // keep the search going.
  162. search = search[commonPrefix:]
  163. continue
  164. }
  165. // Split the node
  166. child := &node{
  167. typ: ntStatic,
  168. prefix: search[:commonPrefix],
  169. }
  170. parent.replaceChild(search[0], segTail, child)
  171. // Restore the existing node
  172. n.label = n.prefix[commonPrefix]
  173. n.prefix = n.prefix[commonPrefix:]
  174. child.addChild(n, n.prefix)
  175. // If the new key is a subset, set the method/handler on this node and finish.
  176. search = search[commonPrefix:]
  177. if len(search) == 0 {
  178. child.setEndpoint(method, handler, pattern)
  179. return child
  180. }
  181. // Create a new edge for the node
  182. subchild := &node{
  183. typ: ntStatic,
  184. label: search[0],
  185. prefix: search,
  186. }
  187. hn := child.addChild(subchild, search)
  188. hn.setEndpoint(method, handler, pattern)
  189. return hn
  190. }
  191. }
  192. // addChild appends the new `child` node to the tree using the `pattern` as the trie key.
  193. // For a URL router like chi's, we split the static, param, regexp and wildcard segments
  194. // into different nodes. In addition, addChild will recursively call itself until every
  195. // pattern segment is added to the url pattern tree as individual nodes, depending on type.
  196. func (n *node) addChild(child *node, prefix string) *node {
  197. search := prefix
  198. // handler leaf node added to the tree is the child.
  199. // this may be overridden later down the flow
  200. hn := child
  201. // Parse next segment
  202. segTyp, _, segRexpat, segTail, segStartIdx, segEndIdx := patNextSegment(search)
  203. // Add child depending on next up segment
  204. switch segTyp {
  205. case ntStatic:
  206. // Search prefix is all static (that is, has no params in path)
  207. // noop
  208. default:
  209. // Search prefix contains a param, regexp or wildcard
  210. if segTyp == ntRegexp {
  211. rex, err := regexp.Compile(segRexpat)
  212. if err != nil {
  213. panic(fmt.Sprintf("chi: invalid regexp pattern '%s' in route param", segRexpat))
  214. }
  215. child.prefix = segRexpat
  216. child.rex = rex
  217. }
  218. if segStartIdx == 0 {
  219. // Route starts with a param
  220. child.typ = segTyp
  221. if segTyp == ntCatchAll {
  222. segStartIdx = -1
  223. } else {
  224. segStartIdx = segEndIdx
  225. }
  226. if segStartIdx < 0 {
  227. segStartIdx = len(search)
  228. }
  229. child.tail = segTail // for params, we set the tail
  230. if segStartIdx != len(search) {
  231. // add static edge for the remaining part, split the end.
  232. // its not possible to have adjacent param nodes, so its certainly
  233. // going to be a static node next.
  234. search = search[segStartIdx:] // advance search position
  235. nn := &node{
  236. typ: ntStatic,
  237. label: search[0],
  238. prefix: search,
  239. }
  240. hn = child.addChild(nn, search)
  241. }
  242. } else if segStartIdx > 0 {
  243. // Route has some param
  244. // starts with a static segment
  245. child.typ = ntStatic
  246. child.prefix = search[:segStartIdx]
  247. child.rex = nil
  248. // add the param edge node
  249. search = search[segStartIdx:]
  250. nn := &node{
  251. typ: segTyp,
  252. label: search[0],
  253. tail: segTail,
  254. }
  255. hn = child.addChild(nn, search)
  256. }
  257. }
  258. n.children[child.typ] = append(n.children[child.typ], child)
  259. n.children[child.typ].Sort()
  260. return hn
  261. }
  262. func (n *node) replaceChild(label, tail byte, child *node) {
  263. for i := 0; i < len(n.children[child.typ]); i++ {
  264. if n.children[child.typ][i].label == label && n.children[child.typ][i].tail == tail {
  265. n.children[child.typ][i] = child
  266. n.children[child.typ][i].label = label
  267. n.children[child.typ][i].tail = tail
  268. return
  269. }
  270. }
  271. panic("chi: replacing missing child")
  272. }
  273. func (n *node) getEdge(ntyp nodeTyp, label, tail byte, prefix string) *node {
  274. nds := n.children[ntyp]
  275. for i := range nds {
  276. if nds[i].label == label && nds[i].tail == tail {
  277. if ntyp == ntRegexp && nds[i].prefix != prefix {
  278. continue
  279. }
  280. return nds[i]
  281. }
  282. }
  283. return nil
  284. }
  285. func (n *node) setEndpoint(method methodTyp, handler http.Handler, pattern string) {
  286. // Set the handler for the method type on the node
  287. if n.endpoints == nil {
  288. n.endpoints = make(endpoints)
  289. }
  290. paramKeys := patParamKeys(pattern)
  291. if method&mSTUB == mSTUB {
  292. n.endpoints.Value(mSTUB).handler = handler
  293. }
  294. if method&mALL == mALL {
  295. h := n.endpoints.Value(mALL)
  296. h.handler = handler
  297. h.pattern = pattern
  298. h.paramKeys = paramKeys
  299. for _, m := range methodMap {
  300. h := n.endpoints.Value(m)
  301. h.handler = handler
  302. h.pattern = pattern
  303. h.paramKeys = paramKeys
  304. }
  305. } else {
  306. h := n.endpoints.Value(method)
  307. h.handler = handler
  308. h.pattern = pattern
  309. h.paramKeys = paramKeys
  310. }
  311. }
  312. func (n *node) FindRoute(rctx *Context, method methodTyp, path string) (*node, endpoints, http.Handler) {
  313. // Reset the context routing pattern and params
  314. rctx.routePattern = ""
  315. rctx.routeParams.Keys = rctx.routeParams.Keys[:0]
  316. rctx.routeParams.Values = rctx.routeParams.Values[:0]
  317. // Find the routing handlers for the path
  318. rn := n.findRoute(rctx, method, path)
  319. if rn == nil {
  320. return nil, nil, nil
  321. }
  322. // Record the routing params in the request lifecycle
  323. rctx.URLParams.Keys = append(rctx.URLParams.Keys, rctx.routeParams.Keys...)
  324. rctx.URLParams.Values = append(rctx.URLParams.Values, rctx.routeParams.Values...)
  325. // Record the routing pattern in the request lifecycle
  326. if rn.endpoints[method].pattern != "" {
  327. rctx.routePattern = rn.endpoints[method].pattern
  328. rctx.RoutePatterns = append(rctx.RoutePatterns, rctx.routePattern)
  329. }
  330. return rn, rn.endpoints, rn.endpoints[method].handler
  331. }
  332. // Recursive edge traversal by checking all nodeTyp groups along the way.
  333. // It's like searching through a multi-dimensional radix trie.
  334. func (n *node) findRoute(rctx *Context, method methodTyp, path string) *node {
  335. nn := n
  336. search := path
  337. for t, nds := range nn.children {
  338. ntyp := nodeTyp(t)
  339. if len(nds) == 0 {
  340. continue
  341. }
  342. var xn *node
  343. xsearch := search
  344. var label byte
  345. if search != "" {
  346. label = search[0]
  347. }
  348. switch ntyp {
  349. case ntStatic:
  350. xn = nds.findEdge(label)
  351. if xn == nil || !strings.HasPrefix(xsearch, xn.prefix) {
  352. continue
  353. }
  354. xsearch = xsearch[len(xn.prefix):]
  355. case ntParam, ntRegexp:
  356. // short-circuit and return no matching route for empty param values
  357. if xsearch == "" {
  358. continue
  359. }
  360. // serially loop through each node grouped by the tail delimiter
  361. for _, xn = range nds {
  362. // label for param nodes is the delimiter byte
  363. p := strings.IndexByte(xsearch, xn.tail)
  364. if p < 0 {
  365. if xn.tail == '/' {
  366. p = len(xsearch)
  367. } else {
  368. continue
  369. }
  370. } else if ntyp == ntRegexp && p == 0 {
  371. continue
  372. }
  373. if ntyp == ntRegexp && xn.rex != nil {
  374. if !xn.rex.MatchString(xsearch[:p]) {
  375. continue
  376. }
  377. } else if strings.IndexByte(xsearch[:p], '/') != -1 {
  378. // avoid a match across path segments
  379. continue
  380. }
  381. prevlen := len(rctx.routeParams.Values)
  382. rctx.routeParams.Values = append(rctx.routeParams.Values, xsearch[:p])
  383. xsearch = xsearch[p:]
  384. if len(xsearch) == 0 {
  385. if xn.isLeaf() {
  386. h := xn.endpoints[method]
  387. if h != nil && h.handler != nil {
  388. rctx.routeParams.Keys = append(rctx.routeParams.Keys, h.paramKeys...)
  389. return xn
  390. }
  391. for endpoints := range xn.endpoints {
  392. if endpoints == mALL || endpoints == mSTUB {
  393. continue
  394. }
  395. rctx.methodsAllowed = append(rctx.methodsAllowed, endpoints)
  396. }
  397. // flag that the routing context found a route, but not a corresponding
  398. // supported method
  399. rctx.methodNotAllowed = true
  400. }
  401. }
  402. // recursively find the next node on this branch
  403. fin := xn.findRoute(rctx, method, xsearch)
  404. if fin != nil {
  405. return fin
  406. }
  407. // not found on this branch, reset vars
  408. rctx.routeParams.Values = rctx.routeParams.Values[:prevlen]
  409. xsearch = search
  410. }
  411. rctx.routeParams.Values = append(rctx.routeParams.Values, "")
  412. default:
  413. // catch-all nodes
  414. rctx.routeParams.Values = append(rctx.routeParams.Values, search)
  415. xn = nds[0]
  416. xsearch = ""
  417. }
  418. if xn == nil {
  419. continue
  420. }
  421. // did we find it yet?
  422. if len(xsearch) == 0 {
  423. if xn.isLeaf() {
  424. h := xn.endpoints[method]
  425. if h != nil && h.handler != nil {
  426. rctx.routeParams.Keys = append(rctx.routeParams.Keys, h.paramKeys...)
  427. return xn
  428. }
  429. for endpoints := range xn.endpoints {
  430. if endpoints == mALL || endpoints == mSTUB {
  431. continue
  432. }
  433. rctx.methodsAllowed = append(rctx.methodsAllowed, endpoints)
  434. }
  435. // flag that the routing context found a route, but not a corresponding
  436. // supported method
  437. rctx.methodNotAllowed = true
  438. }
  439. }
  440. // recursively find the next node..
  441. fin := xn.findRoute(rctx, method, xsearch)
  442. if fin != nil {
  443. return fin
  444. }
  445. // Did not find final handler, let's remove the param here if it was set
  446. if xn.typ > ntStatic {
  447. if len(rctx.routeParams.Values) > 0 {
  448. rctx.routeParams.Values = rctx.routeParams.Values[:len(rctx.routeParams.Values)-1]
  449. }
  450. }
  451. }
  452. return nil
  453. }
  454. func (n *node) findEdge(ntyp nodeTyp, label byte) *node {
  455. nds := n.children[ntyp]
  456. num := len(nds)
  457. idx := 0
  458. switch ntyp {
  459. case ntStatic, ntParam, ntRegexp:
  460. i, j := 0, num-1
  461. for i <= j {
  462. idx = i + (j-i)/2
  463. if label > nds[idx].label {
  464. i = idx + 1
  465. } else if label < nds[idx].label {
  466. j = idx - 1
  467. } else {
  468. i = num // breaks cond
  469. }
  470. }
  471. if nds[idx].label != label {
  472. return nil
  473. }
  474. return nds[idx]
  475. default: // catch all
  476. return nds[idx]
  477. }
  478. }
  479. func (n *node) isLeaf() bool {
  480. return n.endpoints != nil
  481. }
  482. func (n *node) findPattern(pattern string) bool {
  483. nn := n
  484. for _, nds := range nn.children {
  485. if len(nds) == 0 {
  486. continue
  487. }
  488. n = nn.findEdge(nds[0].typ, pattern[0])
  489. if n == nil {
  490. continue
  491. }
  492. var idx int
  493. var xpattern string
  494. switch n.typ {
  495. case ntStatic:
  496. idx = longestPrefix(pattern, n.prefix)
  497. if idx < len(n.prefix) {
  498. continue
  499. }
  500. case ntParam, ntRegexp:
  501. idx = strings.IndexByte(pattern, '}') + 1
  502. case ntCatchAll:
  503. idx = longestPrefix(pattern, "*")
  504. default:
  505. panic("chi: unknown node type")
  506. }
  507. xpattern = pattern[idx:]
  508. if len(xpattern) == 0 {
  509. return true
  510. }
  511. return n.findPattern(xpattern)
  512. }
  513. return false
  514. }
  515. func (n *node) routes() []Route {
  516. rts := []Route{}
  517. n.walk(func(eps endpoints, subroutes Routes) bool {
  518. if eps[mSTUB] != nil && eps[mSTUB].handler != nil && subroutes == nil {
  519. return false
  520. }
  521. // Group methodHandlers by unique patterns
  522. pats := make(map[string]endpoints)
  523. for mt, h := range eps {
  524. if h.pattern == "" {
  525. continue
  526. }
  527. p, ok := pats[h.pattern]
  528. if !ok {
  529. p = endpoints{}
  530. pats[h.pattern] = p
  531. }
  532. p[mt] = h
  533. }
  534. for p, mh := range pats {
  535. hs := make(map[string]http.Handler)
  536. if mh[mALL] != nil && mh[mALL].handler != nil {
  537. hs["*"] = mh[mALL].handler
  538. }
  539. for mt, h := range mh {
  540. if h.handler == nil {
  541. continue
  542. }
  543. if m, ok := reverseMethodMap[mt]; ok {
  544. hs[m] = h.handler
  545. }
  546. }
  547. rt := Route{subroutes, hs, p}
  548. rts = append(rts, rt)
  549. }
  550. return false
  551. })
  552. return rts
  553. }
  554. func (n *node) walk(fn func(eps endpoints, subroutes Routes) bool) bool {
  555. // Visit the leaf values if any
  556. if (n.endpoints != nil || n.subroutes != nil) && fn(n.endpoints, n.subroutes) {
  557. return true
  558. }
  559. // Recurse on the children
  560. for _, ns := range n.children {
  561. for _, cn := range ns {
  562. if cn.walk(fn) {
  563. return true
  564. }
  565. }
  566. }
  567. return false
  568. }
  569. // patNextSegment returns the next segment details from a pattern:
  570. // node type, param key, regexp string, param tail byte, param starting index, param ending index
  571. func patNextSegment(pattern string) (nodeTyp, string, string, byte, int, int) {
  572. ps := strings.Index(pattern, "{")
  573. ws := strings.Index(pattern, "*")
  574. if ps < 0 && ws < 0 {
  575. return ntStatic, "", "", 0, 0, len(pattern) // we return the entire thing
  576. }
  577. // Sanity check
  578. if ps >= 0 && ws >= 0 && ws < ps {
  579. panic("chi: wildcard '*' must be the last pattern in a route, otherwise use a '{param}'")
  580. }
  581. var tail byte = '/' // Default endpoint tail to / byte
  582. if ps >= 0 {
  583. // Param/Regexp pattern is next
  584. nt := ntParam
  585. // Read to closing } taking into account opens and closes in curl count (cc)
  586. cc := 0
  587. pe := ps
  588. for i, c := range pattern[ps:] {
  589. if c == '{' {
  590. cc++
  591. } else if c == '}' {
  592. cc--
  593. if cc == 0 {
  594. pe = ps + i
  595. break
  596. }
  597. }
  598. }
  599. if pe == ps {
  600. panic("chi: route param closing delimiter '}' is missing")
  601. }
  602. key := pattern[ps+1 : pe]
  603. pe++ // set end to next position
  604. if pe < len(pattern) {
  605. tail = pattern[pe]
  606. }
  607. key, rexpat, isRegexp := strings.Cut(key, ":")
  608. if isRegexp {
  609. nt = ntRegexp
  610. }
  611. if len(rexpat) > 0 {
  612. if rexpat[0] != '^' {
  613. rexpat = "^" + rexpat
  614. }
  615. if rexpat[len(rexpat)-1] != '$' {
  616. rexpat += "$"
  617. }
  618. }
  619. return nt, key, rexpat, tail, ps, pe
  620. }
  621. // Wildcard pattern as finale
  622. if ws < len(pattern)-1 {
  623. panic("chi: wildcard '*' must be the last value in a route. trim trailing text or use a '{param}' instead")
  624. }
  625. return ntCatchAll, "*", "", 0, ws, len(pattern)
  626. }
  627. func patParamKeys(pattern string) []string {
  628. pat := pattern
  629. paramKeys := []string{}
  630. for {
  631. ptyp, paramKey, _, _, _, e := patNextSegment(pat)
  632. if ptyp == ntStatic {
  633. return paramKeys
  634. }
  635. for i := 0; i < len(paramKeys); i++ {
  636. if paramKeys[i] == paramKey {
  637. panic(fmt.Sprintf("chi: routing pattern '%s' contains duplicate param key, '%s'", pattern, paramKey))
  638. }
  639. }
  640. paramKeys = append(paramKeys, paramKey)
  641. pat = pat[e:]
  642. }
  643. }
  644. // longestPrefix finds the length of the shared prefix of two strings
  645. func longestPrefix(k1, k2 string) (i int) {
  646. for i = 0; i < min(len(k1), len(k2)); i++ {
  647. if k1[i] != k2[i] {
  648. break
  649. }
  650. }
  651. return
  652. }
  653. type nodes []*node
  654. // Sort the list of nodes by label
  655. func (ns nodes) Sort() { sort.Sort(ns); ns.tailSort() }
  656. func (ns nodes) Len() int { return len(ns) }
  657. func (ns nodes) Swap(i, j int) { ns[i], ns[j] = ns[j], ns[i] }
  658. func (ns nodes) Less(i, j int) bool { return ns[i].label < ns[j].label }
  659. // tailSort pushes nodes with '/' as the tail to the end of the list for param nodes.
  660. // The list order determines the traversal order.
  661. func (ns nodes) tailSort() {
  662. for i := len(ns) - 1; i >= 0; i-- {
  663. if ns[i].typ > ntStatic && ns[i].tail == '/' {
  664. ns.Swap(i, len(ns)-1)
  665. return
  666. }
  667. }
  668. }
  669. func (ns nodes) findEdge(label byte) *node {
  670. num := len(ns)
  671. idx := 0
  672. i, j := 0, num-1
  673. for i <= j {
  674. idx = i + (j-i)/2
  675. if label > ns[idx].label {
  676. i = idx + 1
  677. } else if label < ns[idx].label {
  678. j = idx - 1
  679. } else {
  680. i = num // breaks cond
  681. }
  682. }
  683. if ns[idx].label != label {
  684. return nil
  685. }
  686. return ns[idx]
  687. }
  688. // Route describes the details of a routing handler.
  689. // Handlers map key is an HTTP method
  690. type Route struct {
  691. SubRoutes Routes
  692. Handlers map[string]http.Handler
  693. Pattern string
  694. }
  695. // WalkFunc is the type of the function called for each method and route visited by Walk.
  696. type WalkFunc func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error
  697. // Walk walks any router tree that implements Routes interface.
  698. func Walk(r Routes, walkFn WalkFunc) error {
  699. return walk(r, walkFn, "")
  700. }
  701. func walk(r Routes, walkFn WalkFunc, parentRoute string, parentMw ...func(http.Handler) http.Handler) error {
  702. for _, route := range r.Routes() {
  703. mws := make([]func(http.Handler) http.Handler, len(parentMw))
  704. copy(mws, parentMw)
  705. mws = append(mws, r.Middlewares()...)
  706. if route.SubRoutes != nil {
  707. if err := walk(route.SubRoutes, walkFn, parentRoute+route.Pattern, mws...); err != nil {
  708. return err
  709. }
  710. continue
  711. }
  712. for method, handler := range route.Handlers {
  713. if method == "*" {
  714. // Ignore a "catchAll" method, since we pass down all the specific methods for each route.
  715. continue
  716. }
  717. fullRoute := parentRoute + route.Pattern
  718. fullRoute = strings.Replace(fullRoute, "/*/", "/", -1)
  719. if chain, ok := handler.(*ChainHandler); ok {
  720. if err := walkFn(method, fullRoute, chain.Endpoint, append(mws, chain.Middlewares...)...); err != nil {
  721. return err
  722. }
  723. } else {
  724. if err := walkFn(method, fullRoute, handler, mws...); err != nil {
  725. return err
  726. }
  727. }
  728. }
  729. }
  730. return nil
  731. }