mux.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. "fmt"
  7. "net/http"
  8. "path"
  9. "github.com/gorilla/context"
  10. )
  11. // NewRouter returns a new router instance.
  12. func NewRouter() *Router {
  13. return &Router{namedRoutes: make(map[string]*Route), KeepContext: false}
  14. }
  15. // Router registers routes to be matched and dispatches a handler.
  16. //
  17. // It implements the http.Handler interface, so it can be registered to serve
  18. // requests:
  19. //
  20. // var router = mux.NewRouter()
  21. //
  22. // func main() {
  23. // http.Handle("/", router)
  24. // }
  25. //
  26. // Or, for Google App Engine, register it in a init() function:
  27. //
  28. // func init() {
  29. // http.Handle("/", router)
  30. // }
  31. //
  32. // This will send all incoming requests to the router.
  33. type Router struct {
  34. // Configurable Handler to be used when no route matches.
  35. NotFoundHandler http.Handler
  36. // Parent route, if this is a subrouter.
  37. parent parentRoute
  38. // Routes to be matched, in order.
  39. routes []*Route
  40. // Routes by name for URL building.
  41. namedRoutes map[string]*Route
  42. // See Router.StrictSlash(). This defines the flag for new routes.
  43. strictSlash bool
  44. // If true, do not clear the request context after handling the request
  45. KeepContext bool
  46. }
  47. // Match matches registered routes against the request.
  48. func (r *Router) Match(req *http.Request, match *RouteMatch) bool {
  49. for _, route := range r.routes {
  50. if route.Match(req, match) {
  51. return true
  52. }
  53. }
  54. return false
  55. }
  56. // ServeHTTP dispatches the handler registered in the matched route.
  57. //
  58. // When there is a match, the route variables can be retrieved calling
  59. // mux.Vars(request).
  60. func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  61. // Clean path to canonical form and redirect.
  62. if p := cleanPath(req.URL.Path); p != req.URL.Path {
  63. w.Header().Set("Location", p)
  64. w.WriteHeader(http.StatusMovedPermanently)
  65. return
  66. }
  67. var match RouteMatch
  68. var handler http.Handler
  69. if r.Match(req, &match) {
  70. handler = match.Handler
  71. setVars(req, match.Vars)
  72. setCurrentRoute(req, match.Route)
  73. }
  74. if handler == nil {
  75. if r.NotFoundHandler == nil {
  76. r.NotFoundHandler = http.NotFoundHandler()
  77. }
  78. handler = r.NotFoundHandler
  79. }
  80. if !r.KeepContext {
  81. defer context.Clear(req)
  82. }
  83. handler.ServeHTTP(w, req)
  84. }
  85. // Get returns a route registered with the given name.
  86. func (r *Router) Get(name string) *Route {
  87. return r.getNamedRoutes()[name]
  88. }
  89. // GetRoute returns a route registered with the given name. This method
  90. // was renamed to Get() and remains here for backwards compatibility.
  91. func (r *Router) GetRoute(name string) *Route {
  92. return r.getNamedRoutes()[name]
  93. }
  94. // StrictSlash defines the slash behavior for new routes.
  95. //
  96. // When true, if the route path is "/path/", accessing "/path" will redirect
  97. // to the former and vice versa.
  98. //
  99. // Special case: when a route sets a path prefix, strict slash is
  100. // automatically set to false for that route because the redirect behavior
  101. // can't be determined for prefixes.
  102. func (r *Router) StrictSlash(value bool) *Router {
  103. r.strictSlash = value
  104. return r
  105. }
  106. // ----------------------------------------------------------------------------
  107. // parentRoute
  108. // ----------------------------------------------------------------------------
  109. // getNamedRoutes returns the map where named routes are registered.
  110. func (r *Router) getNamedRoutes() map[string]*Route {
  111. if r.namedRoutes == nil {
  112. if r.parent != nil {
  113. r.namedRoutes = r.parent.getNamedRoutes()
  114. } else {
  115. r.namedRoutes = make(map[string]*Route)
  116. }
  117. }
  118. return r.namedRoutes
  119. }
  120. // getRegexpGroup returns regexp definitions from the parent route, if any.
  121. func (r *Router) getRegexpGroup() *routeRegexpGroup {
  122. if r.parent != nil {
  123. return r.parent.getRegexpGroup()
  124. }
  125. return nil
  126. }
  127. // ----------------------------------------------------------------------------
  128. // Route factories
  129. // ----------------------------------------------------------------------------
  130. // NewRoute registers an empty route.
  131. func (r *Router) NewRoute() *Route {
  132. route := &Route{parent: r, strictSlash: r.strictSlash}
  133. r.routes = append(r.routes, route)
  134. return route
  135. }
  136. // Handle registers a new route with a matcher for the URL path.
  137. // See Route.Path() and Route.Handler().
  138. func (r *Router) Handle(path string, handler http.Handler) *Route {
  139. return r.NewRoute().Path(path).Handler(handler)
  140. }
  141. // HandleFunc registers a new route with a matcher for the URL path.
  142. // See Route.Path() and Route.HandlerFunc().
  143. func (r *Router) HandleFunc(path string, f func(http.ResponseWriter,
  144. *http.Request)) *Route {
  145. return r.NewRoute().Path(path).HandlerFunc(f)
  146. }
  147. // Headers registers a new route with a matcher for request header values.
  148. // See Route.Headers().
  149. func (r *Router) Headers(pairs ...string) *Route {
  150. return r.NewRoute().Headers(pairs...)
  151. }
  152. // Host registers a new route with a matcher for the URL host.
  153. // See Route.Host().
  154. func (r *Router) Host(tpl string) *Route {
  155. return r.NewRoute().Host(tpl)
  156. }
  157. // MatcherFunc registers a new route with a custom matcher function.
  158. // See Route.MatcherFunc().
  159. func (r *Router) MatcherFunc(f MatcherFunc) *Route {
  160. return r.NewRoute().MatcherFunc(f)
  161. }
  162. // Methods registers a new route with a matcher for HTTP methods.
  163. // See Route.Methods().
  164. func (r *Router) Methods(methods ...string) *Route {
  165. return r.NewRoute().Methods(methods...)
  166. }
  167. // Path registers a new route with a matcher for the URL path.
  168. // See Route.Path().
  169. func (r *Router) Path(tpl string) *Route {
  170. return r.NewRoute().Path(tpl)
  171. }
  172. // PathPrefix registers a new route with a matcher for the URL path prefix.
  173. // See Route.PathPrefix().
  174. func (r *Router) PathPrefix(tpl string) *Route {
  175. return r.NewRoute().PathPrefix(tpl)
  176. }
  177. // Queries registers a new route with a matcher for URL query values.
  178. // See Route.Queries().
  179. func (r *Router) Queries(pairs ...string) *Route {
  180. return r.NewRoute().Queries(pairs...)
  181. }
  182. // Schemes registers a new route with a matcher for URL schemes.
  183. // See Route.Schemes().
  184. func (r *Router) Schemes(schemes ...string) *Route {
  185. return r.NewRoute().Schemes(schemes...)
  186. }
  187. // ----------------------------------------------------------------------------
  188. // Context
  189. // ----------------------------------------------------------------------------
  190. // RouteMatch stores information about a matched route.
  191. type RouteMatch struct {
  192. Route *Route
  193. Handler http.Handler
  194. Vars map[string]string
  195. }
  196. type contextKey int
  197. const (
  198. varsKey contextKey = iota
  199. routeKey
  200. )
  201. // Vars returns the route variables for the current request, if any.
  202. func Vars(r *http.Request) map[string]string {
  203. if rv := context.Get(r, varsKey); rv != nil {
  204. return rv.(map[string]string)
  205. }
  206. return nil
  207. }
  208. // CurrentRoute returns the matched route for the current request, if any.
  209. func CurrentRoute(r *http.Request) *Route {
  210. if rv := context.Get(r, routeKey); rv != nil {
  211. return rv.(*Route)
  212. }
  213. return nil
  214. }
  215. func setVars(r *http.Request, val interface{}) {
  216. context.Set(r, varsKey, val)
  217. }
  218. func setCurrentRoute(r *http.Request, val interface{}) {
  219. context.Set(r, routeKey, val)
  220. }
  221. // ----------------------------------------------------------------------------
  222. // Helpers
  223. // ----------------------------------------------------------------------------
  224. // cleanPath returns the canonical path for p, eliminating . and .. elements.
  225. // Borrowed from the net/http package.
  226. func cleanPath(p string) string {
  227. if p == "" {
  228. return "/"
  229. }
  230. if p[0] != '/' {
  231. p = "/" + p
  232. }
  233. np := path.Clean(p)
  234. // path.Clean removes trailing slash except for root;
  235. // put the trailing slash back if necessary.
  236. if p[len(p)-1] == '/' && np != "/" {
  237. np += "/"
  238. }
  239. return np
  240. }
  241. // uniqueVars returns an error if two slices contain duplicated strings.
  242. func uniqueVars(s1, s2 []string) error {
  243. for _, v1 := range s1 {
  244. for _, v2 := range s2 {
  245. if v1 == v2 {
  246. return fmt.Errorf("mux: duplicated route variable %q", v2)
  247. }
  248. }
  249. }
  250. return nil
  251. }
  252. // mapFromPairs converts variadic string parameters to a string map.
  253. func mapFromPairs(pairs ...string) (map[string]string, error) {
  254. length := len(pairs)
  255. if length%2 != 0 {
  256. return nil, fmt.Errorf(
  257. "mux: number of parameters must be multiple of 2, got %v", pairs)
  258. }
  259. m := make(map[string]string, length/2)
  260. for i := 0; i < length; i += 2 {
  261. m[pairs[i]] = pairs[i+1]
  262. }
  263. return m, nil
  264. }
  265. // matchInArray returns true if the given string value is in the array.
  266. func matchInArray(arr []string, value string) bool {
  267. for _, v := range arr {
  268. if v == value {
  269. return true
  270. }
  271. }
  272. return false
  273. }
  274. // matchMap returns true if the given key/value pairs exist in a given map.
  275. func matchMap(toCheck map[string]string, toMatch map[string][]string,
  276. canonicalKey bool) bool {
  277. for k, v := range toCheck {
  278. // Check if key exists.
  279. if canonicalKey {
  280. k = http.CanonicalHeaderKey(k)
  281. }
  282. if values := toMatch[k]; values == nil {
  283. return false
  284. } else if v != "" {
  285. // If value was defined as an empty string we only check that the
  286. // key exists. Otherwise we also check for equality.
  287. valueExists := false
  288. for _, value := range values {
  289. if v == value {
  290. valueExists = true
  291. break
  292. }
  293. }
  294. if !valueExists {
  295. return false
  296. }
  297. }
  298. }
  299. return true
  300. }