mux.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. // Copyright 2012 The Gorilla Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package mux
  5. import (
  6. "errors"
  7. "fmt"
  8. "net/http"
  9. "path"
  10. "regexp"
  11. )
  12. var (
  13. ErrMethodMismatch = errors.New("method is not allowed")
  14. ErrNotFound = errors.New("no matching route was found")
  15. )
  16. // NewRouter returns a new router instance.
  17. func NewRouter() *Router {
  18. return &Router{namedRoutes: make(map[string]*Route), KeepContext: false}
  19. }
  20. // Router registers routes to be matched and dispatches a handler.
  21. //
  22. // It implements the http.Handler interface, so it can be registered to serve
  23. // requests:
  24. //
  25. // var router = mux.NewRouter()
  26. //
  27. // func main() {
  28. // http.Handle("/", router)
  29. // }
  30. //
  31. // Or, for Google App Engine, register it in a init() function:
  32. //
  33. // func init() {
  34. // http.Handle("/", router)
  35. // }
  36. //
  37. // This will send all incoming requests to the router.
  38. type Router struct {
  39. // Configurable Handler to be used when no route matches.
  40. NotFoundHandler http.Handler
  41. // Configurable Handler to be used when the request method does not match the route.
  42. MethodNotAllowedHandler http.Handler
  43. // Parent route, if this is a subrouter.
  44. parent parentRoute
  45. // Routes to be matched, in order.
  46. routes []*Route
  47. // Routes by name for URL building.
  48. namedRoutes map[string]*Route
  49. // See Router.StrictSlash(). This defines the flag for new routes.
  50. strictSlash bool
  51. // See Router.SkipClean(). This defines the flag for new routes.
  52. skipClean bool
  53. // If true, do not clear the request context after handling the request.
  54. // This has no effect when go1.7+ is used, since the context is stored
  55. // on the request itself.
  56. KeepContext bool
  57. // see Router.UseEncodedPath(). This defines a flag for all routes.
  58. useEncodedPath bool
  59. }
  60. // Match attempts to match the given request against the router's registered routes.
  61. //
  62. // If the request matches a route of this router or one of its subrouters the Route,
  63. // Handler, and Vars fields of the the match argument are filled and this function
  64. // returns true.
  65. //
  66. // If the request does not match any of this router's or its subrouters' routes
  67. // then this function returns false. If available, a reason for the match failure
  68. // will be filled in the match argument's MatchErr field. If the match failure type
  69. // (eg: not found) has a registered handler, the handler is assigned to the Handler
  70. // field of the match argument.
  71. func (r *Router) Match(req *http.Request, match *RouteMatch) bool {
  72. for _, route := range r.routes {
  73. if route.Match(req, match) {
  74. return true
  75. }
  76. }
  77. if match.MatchErr == ErrMethodMismatch {
  78. if r.MethodNotAllowedHandler != nil {
  79. match.Handler = r.MethodNotAllowedHandler
  80. return true
  81. } else {
  82. return false
  83. }
  84. }
  85. // Closest match for a router (includes sub-routers)
  86. if r.NotFoundHandler != nil {
  87. match.Handler = r.NotFoundHandler
  88. match.MatchErr = ErrNotFound
  89. return true
  90. }
  91. match.MatchErr = ErrNotFound
  92. return false
  93. }
  94. // ServeHTTP dispatches the handler registered in the matched route.
  95. //
  96. // When there is a match, the route variables can be retrieved calling
  97. // mux.Vars(request).
  98. func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  99. if !r.skipClean {
  100. path := req.URL.Path
  101. if r.useEncodedPath {
  102. path = req.URL.EscapedPath()
  103. }
  104. // Clean path to canonical form and redirect.
  105. if p := cleanPath(path); p != path {
  106. // Added 3 lines (Philip Schlump) - It was dropping the query string and #whatever from query.
  107. // This matches with fix in go 1.2 r.c. 4 for same problem. Go Issue:
  108. // http://code.google.com/p/go/issues/detail?id=5252
  109. url := *req.URL
  110. url.Path = p
  111. p = url.String()
  112. w.Header().Set("Location", p)
  113. w.WriteHeader(http.StatusMovedPermanently)
  114. return
  115. }
  116. }
  117. var match RouteMatch
  118. var handler http.Handler
  119. if r.Match(req, &match) {
  120. handler = match.Handler
  121. req = setVars(req, match.Vars)
  122. req = setCurrentRoute(req, match.Route)
  123. }
  124. if handler == nil && match.MatchErr == ErrMethodMismatch {
  125. handler = methodNotAllowedHandler()
  126. }
  127. if handler == nil {
  128. handler = http.NotFoundHandler()
  129. }
  130. if !r.KeepContext {
  131. defer contextClear(req)
  132. }
  133. handler.ServeHTTP(w, req)
  134. }
  135. // Get returns a route registered with the given name.
  136. func (r *Router) Get(name string) *Route {
  137. return r.getNamedRoutes()[name]
  138. }
  139. // GetRoute returns a route registered with the given name. This method
  140. // was renamed to Get() and remains here for backwards compatibility.
  141. func (r *Router) GetRoute(name string) *Route {
  142. return r.getNamedRoutes()[name]
  143. }
  144. // StrictSlash defines the trailing slash behavior for new routes. The initial
  145. // value is false.
  146. //
  147. // When true, if the route path is "/path/", accessing "/path" will redirect
  148. // to the former and vice versa. In other words, your application will always
  149. // see the path as specified in the route.
  150. //
  151. // When false, if the route path is "/path", accessing "/path/" will not match
  152. // this route and vice versa.
  153. //
  154. // Special case: when a route sets a path prefix using the PathPrefix() method,
  155. // strict slash is ignored for that route because the redirect behavior can't
  156. // be determined from a prefix alone. However, any subrouters created from that
  157. // route inherit the original StrictSlash setting.
  158. func (r *Router) StrictSlash(value bool) *Router {
  159. r.strictSlash = value
  160. return r
  161. }
  162. // SkipClean defines the path cleaning behaviour for new routes. The initial
  163. // value is false. Users should be careful about which routes are not cleaned
  164. //
  165. // When true, if the route path is "/path//to", it will remain with the double
  166. // slash. This is helpful if you have a route like: /fetch/http://xkcd.com/534/
  167. //
  168. // When false, the path will be cleaned, so /fetch/http://xkcd.com/534/ will
  169. // become /fetch/http/xkcd.com/534
  170. func (r *Router) SkipClean(value bool) *Router {
  171. r.skipClean = value
  172. return r
  173. }
  174. // UseEncodedPath tells the router to match the encoded original path
  175. // to the routes.
  176. // For eg. "/path/foo%2Fbar/to" will match the path "/path/{var}/to".
  177. //
  178. // If not called, the router will match the unencoded path to the routes.
  179. // For eg. "/path/foo%2Fbar/to" will match the path "/path/foo/bar/to"
  180. func (r *Router) UseEncodedPath() *Router {
  181. r.useEncodedPath = true
  182. return r
  183. }
  184. // ----------------------------------------------------------------------------
  185. // parentRoute
  186. // ----------------------------------------------------------------------------
  187. func (r *Router) getBuildScheme() string {
  188. if r.parent != nil {
  189. return r.parent.getBuildScheme()
  190. }
  191. return ""
  192. }
  193. // getNamedRoutes returns the map where named routes are registered.
  194. func (r *Router) getNamedRoutes() map[string]*Route {
  195. if r.namedRoutes == nil {
  196. if r.parent != nil {
  197. r.namedRoutes = r.parent.getNamedRoutes()
  198. } else {
  199. r.namedRoutes = make(map[string]*Route)
  200. }
  201. }
  202. return r.namedRoutes
  203. }
  204. // getRegexpGroup returns regexp definitions from the parent route, if any.
  205. func (r *Router) getRegexpGroup() *routeRegexpGroup {
  206. if r.parent != nil {
  207. return r.parent.getRegexpGroup()
  208. }
  209. return nil
  210. }
  211. func (r *Router) buildVars(m map[string]string) map[string]string {
  212. if r.parent != nil {
  213. m = r.parent.buildVars(m)
  214. }
  215. return m
  216. }
  217. // ----------------------------------------------------------------------------
  218. // Route factories
  219. // ----------------------------------------------------------------------------
  220. // NewRoute registers an empty route.
  221. func (r *Router) NewRoute() *Route {
  222. route := &Route{parent: r, strictSlash: r.strictSlash, skipClean: r.skipClean, useEncodedPath: r.useEncodedPath}
  223. r.routes = append(r.routes, route)
  224. return route
  225. }
  226. // Handle registers a new route with a matcher for the URL path.
  227. // See Route.Path() and Route.Handler().
  228. func (r *Router) Handle(path string, handler http.Handler) *Route {
  229. return r.NewRoute().Path(path).Handler(handler)
  230. }
  231. // HandleFunc registers a new route with a matcher for the URL path.
  232. // See Route.Path() and Route.HandlerFunc().
  233. func (r *Router) HandleFunc(path string, f func(http.ResponseWriter,
  234. *http.Request)) *Route {
  235. return r.NewRoute().Path(path).HandlerFunc(f)
  236. }
  237. // Headers registers a new route with a matcher for request header values.
  238. // See Route.Headers().
  239. func (r *Router) Headers(pairs ...string) *Route {
  240. return r.NewRoute().Headers(pairs...)
  241. }
  242. // Host registers a new route with a matcher for the URL host.
  243. // See Route.Host().
  244. func (r *Router) Host(tpl string) *Route {
  245. return r.NewRoute().Host(tpl)
  246. }
  247. // MatcherFunc registers a new route with a custom matcher function.
  248. // See Route.MatcherFunc().
  249. func (r *Router) MatcherFunc(f MatcherFunc) *Route {
  250. return r.NewRoute().MatcherFunc(f)
  251. }
  252. // Methods registers a new route with a matcher for HTTP methods.
  253. // See Route.Methods().
  254. func (r *Router) Methods(methods ...string) *Route {
  255. return r.NewRoute().Methods(methods...)
  256. }
  257. // Path registers a new route with a matcher for the URL path.
  258. // See Route.Path().
  259. func (r *Router) Path(tpl string) *Route {
  260. return r.NewRoute().Path(tpl)
  261. }
  262. // PathPrefix registers a new route with a matcher for the URL path prefix.
  263. // See Route.PathPrefix().
  264. func (r *Router) PathPrefix(tpl string) *Route {
  265. return r.NewRoute().PathPrefix(tpl)
  266. }
  267. // Queries registers a new route with a matcher for URL query values.
  268. // See Route.Queries().
  269. func (r *Router) Queries(pairs ...string) *Route {
  270. return r.NewRoute().Queries(pairs...)
  271. }
  272. // Schemes registers a new route with a matcher for URL schemes.
  273. // See Route.Schemes().
  274. func (r *Router) Schemes(schemes ...string) *Route {
  275. return r.NewRoute().Schemes(schemes...)
  276. }
  277. // BuildVarsFunc registers a new route with a custom function for modifying
  278. // route variables before building a URL.
  279. func (r *Router) BuildVarsFunc(f BuildVarsFunc) *Route {
  280. return r.NewRoute().BuildVarsFunc(f)
  281. }
  282. // Walk walks the router and all its sub-routers, calling walkFn for each route
  283. // in the tree. The routes are walked in the order they were added. Sub-routers
  284. // are explored depth-first.
  285. func (r *Router) Walk(walkFn WalkFunc) error {
  286. return r.walk(walkFn, []*Route{})
  287. }
  288. // SkipRouter is used as a return value from WalkFuncs to indicate that the
  289. // router that walk is about to descend down to should be skipped.
  290. var SkipRouter = errors.New("skip this router")
  291. // WalkFunc is the type of the function called for each route visited by Walk.
  292. // At every invocation, it is given the current route, and the current router,
  293. // and a list of ancestor routes that lead to the current route.
  294. type WalkFunc func(route *Route, router *Router, ancestors []*Route) error
  295. func (r *Router) walk(walkFn WalkFunc, ancestors []*Route) error {
  296. for _, t := range r.routes {
  297. err := walkFn(t, r, ancestors)
  298. if err == SkipRouter {
  299. continue
  300. }
  301. if err != nil {
  302. return err
  303. }
  304. for _, sr := range t.matchers {
  305. if h, ok := sr.(*Router); ok {
  306. ancestors = append(ancestors, t)
  307. err := h.walk(walkFn, ancestors)
  308. if err != nil {
  309. return err
  310. }
  311. ancestors = ancestors[:len(ancestors)-1]
  312. }
  313. }
  314. if h, ok := t.handler.(*Router); ok {
  315. ancestors = append(ancestors, t)
  316. err := h.walk(walkFn, ancestors)
  317. if err != nil {
  318. return err
  319. }
  320. ancestors = ancestors[:len(ancestors)-1]
  321. }
  322. }
  323. return nil
  324. }
  325. // ----------------------------------------------------------------------------
  326. // Context
  327. // ----------------------------------------------------------------------------
  328. // RouteMatch stores information about a matched route.
  329. type RouteMatch struct {
  330. Route *Route
  331. Handler http.Handler
  332. Vars map[string]string
  333. // MatchErr is set to appropriate matching error
  334. // It is set to ErrMethodMismatch if there is a mismatch in
  335. // the request method and route method
  336. MatchErr error
  337. }
  338. type contextKey int
  339. const (
  340. varsKey contextKey = iota
  341. routeKey
  342. )
  343. // Vars returns the route variables for the current request, if any.
  344. func Vars(r *http.Request) map[string]string {
  345. if rv := contextGet(r, varsKey); rv != nil {
  346. return rv.(map[string]string)
  347. }
  348. return nil
  349. }
  350. // CurrentRoute returns the matched route for the current request, if any.
  351. // This only works when called inside the handler of the matched route
  352. // because the matched route is stored in the request context which is cleared
  353. // after the handler returns, unless the KeepContext option is set on the
  354. // Router.
  355. func CurrentRoute(r *http.Request) *Route {
  356. if rv := contextGet(r, routeKey); rv != nil {
  357. return rv.(*Route)
  358. }
  359. return nil
  360. }
  361. func setVars(r *http.Request, val interface{}) *http.Request {
  362. return contextSet(r, varsKey, val)
  363. }
  364. func setCurrentRoute(r *http.Request, val interface{}) *http.Request {
  365. return contextSet(r, routeKey, val)
  366. }
  367. // ----------------------------------------------------------------------------
  368. // Helpers
  369. // ----------------------------------------------------------------------------
  370. // cleanPath returns the canonical path for p, eliminating . and .. elements.
  371. // Borrowed from the net/http package.
  372. func cleanPath(p string) string {
  373. if p == "" {
  374. return "/"
  375. }
  376. if p[0] != '/' {
  377. p = "/" + p
  378. }
  379. np := path.Clean(p)
  380. // path.Clean removes trailing slash except for root;
  381. // put the trailing slash back if necessary.
  382. if p[len(p)-1] == '/' && np != "/" {
  383. np += "/"
  384. }
  385. return np
  386. }
  387. // uniqueVars returns an error if two slices contain duplicated strings.
  388. func uniqueVars(s1, s2 []string) error {
  389. for _, v1 := range s1 {
  390. for _, v2 := range s2 {
  391. if v1 == v2 {
  392. return fmt.Errorf("mux: duplicated route variable %q", v2)
  393. }
  394. }
  395. }
  396. return nil
  397. }
  398. // checkPairs returns the count of strings passed in, and an error if
  399. // the count is not an even number.
  400. func checkPairs(pairs ...string) (int, error) {
  401. length := len(pairs)
  402. if length%2 != 0 {
  403. return length, fmt.Errorf(
  404. "mux: number of parameters must be multiple of 2, got %v", pairs)
  405. }
  406. return length, nil
  407. }
  408. // mapFromPairsToString converts variadic string parameters to a
  409. // string to string map.
  410. func mapFromPairsToString(pairs ...string) (map[string]string, error) {
  411. length, err := checkPairs(pairs...)
  412. if err != nil {
  413. return nil, err
  414. }
  415. m := make(map[string]string, length/2)
  416. for i := 0; i < length; i += 2 {
  417. m[pairs[i]] = pairs[i+1]
  418. }
  419. return m, nil
  420. }
  421. // mapFromPairsToRegex converts variadic string parameters to a
  422. // string to regex map.
  423. func mapFromPairsToRegex(pairs ...string) (map[string]*regexp.Regexp, error) {
  424. length, err := checkPairs(pairs...)
  425. if err != nil {
  426. return nil, err
  427. }
  428. m := make(map[string]*regexp.Regexp, length/2)
  429. for i := 0; i < length; i += 2 {
  430. regex, err := regexp.Compile(pairs[i+1])
  431. if err != nil {
  432. return nil, err
  433. }
  434. m[pairs[i]] = regex
  435. }
  436. return m, nil
  437. }
  438. // matchInArray returns true if the given string value is in the array.
  439. func matchInArray(arr []string, value string) bool {
  440. for _, v := range arr {
  441. if v == value {
  442. return true
  443. }
  444. }
  445. return false
  446. }
  447. // matchMapWithString returns true if the given key/value pairs exist in a given map.
  448. func matchMapWithString(toCheck map[string]string, toMatch map[string][]string, canonicalKey bool) bool {
  449. for k, v := range toCheck {
  450. // Check if key exists.
  451. if canonicalKey {
  452. k = http.CanonicalHeaderKey(k)
  453. }
  454. if values := toMatch[k]; values == nil {
  455. return false
  456. } else if v != "" {
  457. // If value was defined as an empty string we only check that the
  458. // key exists. Otherwise we also check for equality.
  459. valueExists := false
  460. for _, value := range values {
  461. if v == value {
  462. valueExists = true
  463. break
  464. }
  465. }
  466. if !valueExists {
  467. return false
  468. }
  469. }
  470. }
  471. return true
  472. }
  473. // matchMapWithRegex returns true if the given key/value pairs exist in a given map compiled against
  474. // the given regex
  475. func matchMapWithRegex(toCheck map[string]*regexp.Regexp, toMatch map[string][]string, canonicalKey bool) bool {
  476. for k, v := range toCheck {
  477. // Check if key exists.
  478. if canonicalKey {
  479. k = http.CanonicalHeaderKey(k)
  480. }
  481. if values := toMatch[k]; values == nil {
  482. return false
  483. } else if v != nil {
  484. // If value was defined as an empty string we only check that the
  485. // key exists. Otherwise we also check for equality.
  486. valueExists := false
  487. for _, value := range values {
  488. if v.MatchString(value) {
  489. valueExists = true
  490. break
  491. }
  492. }
  493. if !valueExists {
  494. return false
  495. }
  496. }
  497. }
  498. return true
  499. }
  500. // methodNotAllowed replies to the request with an HTTP status code 405.
  501. func methodNotAllowed(w http.ResponseWriter, r *http.Request) {
  502. w.WriteHeader(http.StatusMethodNotAllowed)
  503. }
  504. // methodNotAllowedHandler returns a simple request handler
  505. // that replies to each request with a status code 405.
  506. func methodNotAllowedHandler() http.Handler { return http.HandlerFunc(methodNotAllowed) }