mux.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. package chi
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "strings"
  7. "sync"
  8. )
  9. var _ Router = &Mux{}
  10. // Mux is a simple HTTP route multiplexer that parses a request path,
  11. // records any URL params, and executes an end handler. It implements
  12. // the http.Handler interface and is friendly with the standard library.
  13. //
  14. // Mux is designed to be fast, minimal and offer a powerful API for building
  15. // modular and composable HTTP services with a large set of handlers. It's
  16. // particularly useful for writing large REST API services that break a handler
  17. // into many smaller parts composed of middlewares and end handlers.
  18. type Mux struct {
  19. // The computed mux handler made of the chained middleware stack and
  20. // the tree router
  21. handler http.Handler
  22. // The radix trie router
  23. tree *node
  24. // Custom method not allowed handler
  25. methodNotAllowedHandler http.HandlerFunc
  26. // A reference to the parent mux used by subrouters when mounting
  27. // to a parent mux
  28. parent *Mux
  29. // Routing context pool
  30. pool *sync.Pool
  31. // Custom route not found handler
  32. notFoundHandler http.HandlerFunc
  33. // The middleware stack
  34. middlewares []func(http.Handler) http.Handler
  35. // Controls the behaviour of middleware chain generation when a mux
  36. // is registered as an inline group inside another mux.
  37. inline bool
  38. }
  39. // NewMux returns a newly initialized Mux object that implements the Router
  40. // interface.
  41. func NewMux() *Mux {
  42. mux := &Mux{tree: &node{}, pool: &sync.Pool{}}
  43. mux.pool.New = func() interface{} {
  44. return NewRouteContext()
  45. }
  46. return mux
  47. }
  48. // ServeHTTP is the single method of the http.Handler interface that makes
  49. // Mux interoperable with the standard library. It uses a sync.Pool to get and
  50. // reuse routing contexts for each request.
  51. func (mx *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  52. // Ensure the mux has some routes defined on the mux
  53. if mx.handler == nil {
  54. mx.NotFoundHandler().ServeHTTP(w, r)
  55. return
  56. }
  57. // Check if a routing context already exists from a parent router.
  58. rctx, _ := r.Context().Value(RouteCtxKey).(*Context)
  59. if rctx != nil {
  60. mx.handler.ServeHTTP(w, r)
  61. return
  62. }
  63. // Fetch a RouteContext object from the sync pool, and call the computed
  64. // mx.handler that is comprised of mx.middlewares + mx.routeHTTP.
  65. // Once the request is finished, reset the routing context and put it back
  66. // into the pool for reuse from another request.
  67. rctx = mx.pool.Get().(*Context)
  68. rctx.Reset()
  69. rctx.Routes = mx
  70. rctx.parentCtx = r.Context()
  71. // NOTE: r.WithContext() causes 2 allocations and context.WithValue() causes 1 allocation
  72. r = r.WithContext(context.WithValue(r.Context(), RouteCtxKey, rctx))
  73. // Serve the request and once its done, put the request context back in the sync pool
  74. mx.handler.ServeHTTP(w, r)
  75. mx.pool.Put(rctx)
  76. }
  77. // Use appends a middleware handler to the Mux middleware stack.
  78. //
  79. // The middleware stack for any Mux will execute before searching for a matching
  80. // route to a specific handler, which provides opportunity to respond early,
  81. // change the course of the request execution, or set request-scoped values for
  82. // the next http.Handler.
  83. func (mx *Mux) Use(middlewares ...func(http.Handler) http.Handler) {
  84. if mx.handler != nil {
  85. panic("chi: all middlewares must be defined before routes on a mux")
  86. }
  87. mx.middlewares = append(mx.middlewares, middlewares...)
  88. }
  89. // Handle adds the route `pattern` that matches any http method to
  90. // execute the `handler` http.Handler.
  91. func (mx *Mux) Handle(pattern string, handler http.Handler) {
  92. if i := strings.IndexAny(pattern, " \t"); i >= 0 {
  93. method, rest := pattern[:i], strings.TrimLeft(pattern[i+1:], " \t")
  94. mx.Method(method, rest, handler)
  95. return
  96. }
  97. mx.handle(mALL, pattern, handler)
  98. }
  99. // HandleFunc adds the route `pattern` that matches any http method to
  100. // execute the `handlerFn` http.HandlerFunc.
  101. func (mx *Mux) HandleFunc(pattern string, handlerFn http.HandlerFunc) {
  102. mx.Handle(pattern, handlerFn)
  103. }
  104. // Method adds the route `pattern` that matches `method` http method to
  105. // execute the `handler` http.Handler.
  106. func (mx *Mux) Method(method, pattern string, handler http.Handler) {
  107. m, ok := methodMap[strings.ToUpper(method)]
  108. if !ok {
  109. panic(fmt.Sprintf("chi: '%s' http method is not supported.", method))
  110. }
  111. mx.handle(m, pattern, handler)
  112. }
  113. // MethodFunc adds the route `pattern` that matches `method` http method to
  114. // execute the `handlerFn` http.HandlerFunc.
  115. func (mx *Mux) MethodFunc(method, pattern string, handlerFn http.HandlerFunc) {
  116. mx.Method(method, pattern, handlerFn)
  117. }
  118. // Connect adds the route `pattern` that matches a CONNECT http method to
  119. // execute the `handlerFn` http.HandlerFunc.
  120. func (mx *Mux) Connect(pattern string, handlerFn http.HandlerFunc) {
  121. mx.handle(mCONNECT, pattern, handlerFn)
  122. }
  123. // Delete adds the route `pattern` that matches a DELETE http method to
  124. // execute the `handlerFn` http.HandlerFunc.
  125. func (mx *Mux) Delete(pattern string, handlerFn http.HandlerFunc) {
  126. mx.handle(mDELETE, pattern, handlerFn)
  127. }
  128. // Get adds the route `pattern` that matches a GET http method to
  129. // execute the `handlerFn` http.HandlerFunc.
  130. func (mx *Mux) Get(pattern string, handlerFn http.HandlerFunc) {
  131. mx.handle(mGET, pattern, handlerFn)
  132. }
  133. // Head adds the route `pattern` that matches a HEAD http method to
  134. // execute the `handlerFn` http.HandlerFunc.
  135. func (mx *Mux) Head(pattern string, handlerFn http.HandlerFunc) {
  136. mx.handle(mHEAD, pattern, handlerFn)
  137. }
  138. // Options adds the route `pattern` that matches an OPTIONS http method to
  139. // execute the `handlerFn` http.HandlerFunc.
  140. func (mx *Mux) Options(pattern string, handlerFn http.HandlerFunc) {
  141. mx.handle(mOPTIONS, pattern, handlerFn)
  142. }
  143. // Patch adds the route `pattern` that matches a PATCH http method to
  144. // execute the `handlerFn` http.HandlerFunc.
  145. func (mx *Mux) Patch(pattern string, handlerFn http.HandlerFunc) {
  146. mx.handle(mPATCH, pattern, handlerFn)
  147. }
  148. // Post adds the route `pattern` that matches a POST http method to
  149. // execute the `handlerFn` http.HandlerFunc.
  150. func (mx *Mux) Post(pattern string, handlerFn http.HandlerFunc) {
  151. mx.handle(mPOST, pattern, handlerFn)
  152. }
  153. // Put adds the route `pattern` that matches a PUT http method to
  154. // execute the `handlerFn` http.HandlerFunc.
  155. func (mx *Mux) Put(pattern string, handlerFn http.HandlerFunc) {
  156. mx.handle(mPUT, pattern, handlerFn)
  157. }
  158. // Trace adds the route `pattern` that matches a TRACE http method to
  159. // execute the `handlerFn` http.HandlerFunc.
  160. func (mx *Mux) Trace(pattern string, handlerFn http.HandlerFunc) {
  161. mx.handle(mTRACE, pattern, handlerFn)
  162. }
  163. // NotFound sets a custom http.HandlerFunc for routing paths that could
  164. // not be found. The default 404 handler is `http.NotFound`.
  165. func (mx *Mux) NotFound(handlerFn http.HandlerFunc) {
  166. // Build NotFound handler chain
  167. m := mx
  168. hFn := handlerFn
  169. if mx.inline && mx.parent != nil {
  170. m = mx.parent
  171. hFn = Chain(mx.middlewares...).HandlerFunc(hFn).ServeHTTP
  172. }
  173. // Update the notFoundHandler from this point forward
  174. m.notFoundHandler = hFn
  175. m.updateSubRoutes(func(subMux *Mux) {
  176. if subMux.notFoundHandler == nil {
  177. subMux.NotFound(hFn)
  178. }
  179. })
  180. }
  181. // MethodNotAllowed sets a custom http.HandlerFunc for routing paths where the
  182. // method is unresolved. The default handler returns a 405 with an empty body.
  183. func (mx *Mux) MethodNotAllowed(handlerFn http.HandlerFunc) {
  184. // Build MethodNotAllowed handler chain
  185. m := mx
  186. hFn := handlerFn
  187. if mx.inline && mx.parent != nil {
  188. m = mx.parent
  189. hFn = Chain(mx.middlewares...).HandlerFunc(hFn).ServeHTTP
  190. }
  191. // Update the methodNotAllowedHandler from this point forward
  192. m.methodNotAllowedHandler = hFn
  193. m.updateSubRoutes(func(subMux *Mux) {
  194. if subMux.methodNotAllowedHandler == nil {
  195. subMux.MethodNotAllowed(hFn)
  196. }
  197. })
  198. }
  199. // With adds inline middlewares for an endpoint handler.
  200. func (mx *Mux) With(middlewares ...func(http.Handler) http.Handler) Router {
  201. // Similarly as in handle(), we must build the mux handler once additional
  202. // middleware registration isn't allowed for this stack, like now.
  203. if !mx.inline && mx.handler == nil {
  204. mx.updateRouteHandler()
  205. }
  206. // Copy middlewares from parent inline muxs
  207. var mws Middlewares
  208. if mx.inline {
  209. mws = make(Middlewares, len(mx.middlewares))
  210. copy(mws, mx.middlewares)
  211. }
  212. mws = append(mws, middlewares...)
  213. im := &Mux{
  214. pool: mx.pool, inline: true, parent: mx, tree: mx.tree, middlewares: mws,
  215. notFoundHandler: mx.notFoundHandler, methodNotAllowedHandler: mx.methodNotAllowedHandler,
  216. }
  217. return im
  218. }
  219. // Group creates a new inline-Mux with a copy of middleware stack. It's useful
  220. // for a group of handlers along the same routing path that use an additional
  221. // set of middlewares. See _examples/.
  222. func (mx *Mux) Group(fn func(r Router)) Router {
  223. im := mx.With()
  224. if fn != nil {
  225. fn(im)
  226. }
  227. return im
  228. }
  229. // Route creates a new Mux and mounts it along the `pattern` as a subrouter.
  230. // Effectively, this is a short-hand call to Mount. See _examples/.
  231. func (mx *Mux) Route(pattern string, fn func(r Router)) Router {
  232. if fn == nil {
  233. panic(fmt.Sprintf("chi: attempting to Route() a nil subrouter on '%s'", pattern))
  234. }
  235. subRouter := NewRouter()
  236. fn(subRouter)
  237. mx.Mount(pattern, subRouter)
  238. return subRouter
  239. }
  240. // Mount attaches another http.Handler or chi Router as a subrouter along a routing
  241. // path. It's very useful to split up a large API as many independent routers and
  242. // compose them as a single service using Mount. See _examples/.
  243. //
  244. // Note that Mount() simply sets a wildcard along the `pattern` that will continue
  245. // routing at the `handler`, which in most cases is another chi.Router. As a result,
  246. // if you define two Mount() routes on the exact same pattern the mount will panic.
  247. func (mx *Mux) Mount(pattern string, handler http.Handler) {
  248. if handler == nil {
  249. panic(fmt.Sprintf("chi: attempting to Mount() a nil handler on '%s'", pattern))
  250. }
  251. // Provide runtime safety for ensuring a pattern isn't mounted on an existing
  252. // routing pattern.
  253. if mx.tree.findPattern(pattern+"*") || mx.tree.findPattern(pattern+"/*") {
  254. panic(fmt.Sprintf("chi: attempting to Mount() a handler on an existing path, '%s'", pattern))
  255. }
  256. // Assign sub-Router's with the parent not found & method not allowed handler if not specified.
  257. subr, ok := handler.(*Mux)
  258. if ok && subr.notFoundHandler == nil && mx.notFoundHandler != nil {
  259. subr.NotFound(mx.notFoundHandler)
  260. }
  261. if ok && subr.methodNotAllowedHandler == nil && mx.methodNotAllowedHandler != nil {
  262. subr.MethodNotAllowed(mx.methodNotAllowedHandler)
  263. }
  264. mountHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  265. rctx := RouteContext(r.Context())
  266. // shift the url path past the previous subrouter
  267. rctx.RoutePath = mx.nextRoutePath(rctx)
  268. // reset the wildcard URLParam which connects the subrouter
  269. n := len(rctx.URLParams.Keys) - 1
  270. if n >= 0 && rctx.URLParams.Keys[n] == "*" && len(rctx.URLParams.Values) > n {
  271. rctx.URLParams.Values[n] = ""
  272. }
  273. handler.ServeHTTP(w, r)
  274. })
  275. if pattern == "" || pattern[len(pattern)-1] != '/' {
  276. mx.handle(mALL|mSTUB, pattern, mountHandler)
  277. mx.handle(mALL|mSTUB, pattern+"/", mountHandler)
  278. pattern += "/"
  279. }
  280. method := mALL
  281. subroutes, _ := handler.(Routes)
  282. if subroutes != nil {
  283. method |= mSTUB
  284. }
  285. n := mx.handle(method, pattern+"*", mountHandler)
  286. if subroutes != nil {
  287. n.subroutes = subroutes
  288. }
  289. }
  290. // Routes returns a slice of routing information from the tree,
  291. // useful for traversing available routes of a router.
  292. func (mx *Mux) Routes() []Route {
  293. return mx.tree.routes()
  294. }
  295. // Middlewares returns a slice of middleware handler functions.
  296. func (mx *Mux) Middlewares() Middlewares {
  297. return mx.middlewares
  298. }
  299. // Match searches the routing tree for a handler that matches the method/path.
  300. // It's similar to routing a http request, but without executing the handler
  301. // thereafter.
  302. //
  303. // Note: the *Context state is updated during execution, so manage
  304. // the state carefully or make a NewRouteContext().
  305. func (mx *Mux) Match(rctx *Context, method, path string) bool {
  306. return mx.Find(rctx, method, path) != ""
  307. }
  308. // Find searches the routing tree for the pattern that matches
  309. // the method/path.
  310. //
  311. // Note: the *Context state is updated during execution, so manage
  312. // the state carefully or make a NewRouteContext().
  313. func (mx *Mux) Find(rctx *Context, method, path string) string {
  314. m, ok := methodMap[method]
  315. if !ok {
  316. return ""
  317. }
  318. node, _, _ := mx.tree.FindRoute(rctx, m, path)
  319. pattern := rctx.routePattern
  320. if node != nil {
  321. if node.subroutes == nil {
  322. e := node.endpoints[m]
  323. return e.pattern
  324. }
  325. rctx.RoutePath = mx.nextRoutePath(rctx)
  326. subPattern := node.subroutes.Find(rctx, method, rctx.RoutePath)
  327. if subPattern == "" {
  328. return ""
  329. }
  330. pattern = strings.TrimSuffix(pattern, "/*")
  331. pattern += subPattern
  332. }
  333. return pattern
  334. }
  335. // NotFoundHandler returns the default Mux 404 responder whenever a route
  336. // cannot be found.
  337. func (mx *Mux) NotFoundHandler() http.HandlerFunc {
  338. if mx.notFoundHandler != nil {
  339. return mx.notFoundHandler
  340. }
  341. return http.NotFound
  342. }
  343. // MethodNotAllowedHandler returns the default Mux 405 responder whenever
  344. // a method cannot be resolved for a route.
  345. func (mx *Mux) MethodNotAllowedHandler(methodsAllowed ...methodTyp) http.HandlerFunc {
  346. if mx.methodNotAllowedHandler != nil {
  347. return mx.methodNotAllowedHandler
  348. }
  349. return methodNotAllowedHandler(methodsAllowed...)
  350. }
  351. // handle registers a http.Handler in the routing tree for a particular http method
  352. // and routing pattern.
  353. func (mx *Mux) handle(method methodTyp, pattern string, handler http.Handler) *node {
  354. if len(pattern) == 0 || pattern[0] != '/' {
  355. panic(fmt.Sprintf("chi: routing pattern must begin with '/' in '%s'", pattern))
  356. }
  357. // Build the computed routing handler for this routing pattern.
  358. if !mx.inline && mx.handler == nil {
  359. mx.updateRouteHandler()
  360. }
  361. // Build endpoint handler with inline middlewares for the route
  362. var h http.Handler
  363. if mx.inline {
  364. mx.handler = http.HandlerFunc(mx.routeHTTP)
  365. h = Chain(mx.middlewares...).Handler(handler)
  366. } else {
  367. h = handler
  368. }
  369. // Add the endpoint to the tree and return the node
  370. return mx.tree.InsertRoute(method, pattern, h)
  371. }
  372. // routeHTTP routes a http.Request through the Mux routing tree to serve
  373. // the matching handler for a particular http method.
  374. func (mx *Mux) routeHTTP(w http.ResponseWriter, r *http.Request) {
  375. // Grab the route context object
  376. rctx := r.Context().Value(RouteCtxKey).(*Context)
  377. // The request routing path
  378. routePath := rctx.RoutePath
  379. if routePath == "" {
  380. if r.URL.RawPath != "" {
  381. routePath = r.URL.RawPath
  382. } else {
  383. routePath = r.URL.Path
  384. }
  385. if routePath == "" {
  386. routePath = "/"
  387. }
  388. }
  389. // Check if method is supported by chi
  390. if rctx.RouteMethod == "" {
  391. rctx.RouteMethod = r.Method
  392. }
  393. method, ok := methodMap[rctx.RouteMethod]
  394. if !ok {
  395. mx.MethodNotAllowedHandler().ServeHTTP(w, r)
  396. return
  397. }
  398. // Find the route
  399. if _, _, h := mx.tree.FindRoute(rctx, method, routePath); h != nil {
  400. // Set http.Request path values from our request context
  401. for i, key := range rctx.URLParams.Keys {
  402. value := rctx.URLParams.Values[i]
  403. r.SetPathValue(key, value)
  404. }
  405. if supportsPattern {
  406. setPattern(rctx, r)
  407. }
  408. h.ServeHTTP(w, r)
  409. return
  410. }
  411. if rctx.methodNotAllowed {
  412. mx.MethodNotAllowedHandler(rctx.methodsAllowed...).ServeHTTP(w, r)
  413. } else {
  414. mx.NotFoundHandler().ServeHTTP(w, r)
  415. }
  416. }
  417. func (mx *Mux) nextRoutePath(rctx *Context) string {
  418. routePath := "/"
  419. nx := len(rctx.routeParams.Keys) - 1 // index of last param in list
  420. if nx >= 0 && rctx.routeParams.Keys[nx] == "*" && len(rctx.routeParams.Values) > nx {
  421. routePath = "/" + rctx.routeParams.Values[nx]
  422. }
  423. return routePath
  424. }
  425. // Recursively update data on child routers.
  426. func (mx *Mux) updateSubRoutes(fn func(subMux *Mux)) {
  427. for _, r := range mx.tree.routes() {
  428. subMux, ok := r.SubRoutes.(*Mux)
  429. if !ok {
  430. continue
  431. }
  432. fn(subMux)
  433. }
  434. }
  435. // updateRouteHandler builds the single mux handler that is a chain of the middleware
  436. // stack, as defined by calls to Use(), and the tree router (Mux) itself. After this
  437. // point, no other middlewares can be registered on this Mux's stack. But you can still
  438. // compose additional middlewares via Group()'s or using a chained middleware handler.
  439. func (mx *Mux) updateRouteHandler() {
  440. mx.handler = chain(mx.middlewares, http.HandlerFunc(mx.routeHTTP))
  441. }
  442. // methodNotAllowedHandler is a helper function to respond with a 405,
  443. // method not allowed. It sets the Allow header with the list of allowed
  444. // methods for the route.
  445. func methodNotAllowedHandler(methodsAllowed ...methodTyp) func(w http.ResponseWriter, r *http.Request) {
  446. return func(w http.ResponseWriter, r *http.Request) {
  447. for _, m := range methodsAllowed {
  448. w.Header().Add("Allow", reverseMethodMap[m])
  449. }
  450. w.WriteHeader(405)
  451. w.Write(nil)
  452. }
  453. }