You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

307 lines
11 KiB

  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. /*
  5. Package mux implements a request router and dispatcher.
  6. The name mux stands for "HTTP request multiplexer". Like the standard
  7. http.ServeMux, mux.Router matches incoming requests against a list of
  8. registered routes and calls a handler for the route that matches the URL
  9. or other conditions. The main features are:
  10. * Requests can be matched based on URL host, path, path prefix, schemes,
  11. header and query values, HTTP methods or using custom matchers.
  12. * URL hosts, paths and query values can have variables with an optional
  13. regular expression.
  14. * Registered URLs can be built, or "reversed", which helps maintaining
  15. references to resources.
  16. * Routes can be used as subrouters: nested routes are only tested if the
  17. parent route matches. This is useful to define groups of routes that
  18. share common conditions like a host, a path prefix or other repeated
  19. attributes. As a bonus, this optimizes request matching.
  20. * It implements the http.Handler interface so it is compatible with the
  21. standard http.ServeMux.
  22. Let's start registering a couple of URL paths and handlers:
  23. func main() {
  24. r := mux.NewRouter()
  25. r.HandleFunc("/", HomeHandler)
  26. r.HandleFunc("/products", ProductsHandler)
  27. r.HandleFunc("/articles", ArticlesHandler)
  28. http.Handle("/", r)
  29. }
  30. Here we register three routes mapping URL paths to handlers. This is
  31. equivalent to how http.HandleFunc() works: if an incoming request URL matches
  32. one of the paths, the corresponding handler is called passing
  33. (http.ResponseWriter, *http.Request) as parameters.
  34. Paths can have variables. They are defined using the format {name} or
  35. {name:pattern}. If a regular expression pattern is not defined, the matched
  36. variable will be anything until the next slash. For example:
  37. r := mux.NewRouter()
  38. r.HandleFunc("/products/{key}", ProductHandler)
  39. r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler)
  40. r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
  41. Groups can be used inside patterns, as long as they are non-capturing (?:re). For example:
  42. r.HandleFunc("/articles/{category}/{sort:(?:asc|desc|new)}", ArticlesCategoryHandler)
  43. The names are used to create a map of route variables which can be retrieved
  44. calling mux.Vars():
  45. vars := mux.Vars(request)
  46. category := vars["category"]
  47. Note that if any capturing groups are present, mux will panic() during parsing. To prevent
  48. this, convert any capturing groups to non-capturing, e.g. change "/{sort:(asc|desc)}" to
  49. "/{sort:(?:asc|desc)}". This is a change from prior versions which behaved unpredictably
  50. when capturing groups were present.
  51. And this is all you need to know about the basic usage. More advanced options
  52. are explained below.
  53. Routes can also be restricted to a domain or subdomain. Just define a host
  54. pattern to be matched. They can also have variables:
  55. r := mux.NewRouter()
  56. // Only matches if domain is "www.example.com".
  57. r.Host("www.example.com")
  58. // Matches a dynamic subdomain.
  59. r.Host("{subdomain:[a-z]+}.domain.com")
  60. There are several other matchers that can be added. To match path prefixes:
  61. r.PathPrefix("/products/")
  62. ...or HTTP methods:
  63. r.Methods("GET", "POST")
  64. ...or URL schemes:
  65. r.Schemes("https")
  66. ...or header values:
  67. r.Headers("X-Requested-With", "XMLHttpRequest")
  68. ...or query values:
  69. r.Queries("key", "value")
  70. ...or to use a custom matcher function:
  71. r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool {
  72. return r.ProtoMajor == 0
  73. })
  74. ...and finally, it is possible to combine several matchers in a single route:
  75. r.HandleFunc("/products", ProductsHandler).
  76. Host("www.example.com").
  77. Methods("GET").
  78. Schemes("http")
  79. Setting the same matching conditions again and again can be boring, so we have
  80. a way to group several routes that share the same requirements.
  81. We call it "subrouting".
  82. For example, let's say we have several URLs that should only match when the
  83. host is "www.example.com". Create a route for that host and get a "subrouter"
  84. from it:
  85. r := mux.NewRouter()
  86. s := r.Host("www.example.com").Subrouter()
  87. Then register routes in the subrouter:
  88. s.HandleFunc("/products/", ProductsHandler)
  89. s.HandleFunc("/products/{key}", ProductHandler)
  90. s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler)
  91. The three URL paths we registered above will only be tested if the domain is
  92. "www.example.com", because the subrouter is tested first. This is not
  93. only convenient, but also optimizes request matching. You can create
  94. subrouters combining any attribute matchers accepted by a route.
  95. Subrouters can be used to create domain or path "namespaces": you define
  96. subrouters in a central place and then parts of the app can register its
  97. paths relatively to a given subrouter.
  98. There's one more thing about subroutes. When a subrouter has a path prefix,
  99. the inner routes use it as base for their paths:
  100. r := mux.NewRouter()
  101. s := r.PathPrefix("/products").Subrouter()
  102. // "/products/"
  103. s.HandleFunc("/", ProductsHandler)
  104. // "/products/{key}/"
  105. s.HandleFunc("/{key}/", ProductHandler)
  106. // "/products/{key}/details"
  107. s.HandleFunc("/{key}/details", ProductDetailsHandler)
  108. Note that the path provided to PathPrefix() represents a "wildcard": calling
  109. PathPrefix("/static/").Handler(...) means that the handler will be passed any
  110. request that matches "/static/*". This makes it easy to serve static files with mux:
  111. func main() {
  112. var dir string
  113. flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir")
  114. flag.Parse()
  115. r := mux.NewRouter()
  116. // This will serve files under http://localhost:8000/static/<filename>
  117. r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir))))
  118. srv := &http.Server{
  119. Handler: r,
  120. Addr: "127.0.0.1:8000",
  121. // Good practice: enforce timeouts for servers you create!
  122. WriteTimeout: 15 * time.Second,
  123. ReadTimeout: 15 * time.Second,
  124. }
  125. log.Fatal(srv.ListenAndServe())
  126. }
  127. Now let's see how to build registered URLs.
  128. Routes can be named. All routes that define a name can have their URLs built,
  129. or "reversed". We define a name calling Name() on a route. For example:
  130. r := mux.NewRouter()
  131. r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
  132. Name("article")
  133. To build a URL, get the route and call the URL() method, passing a sequence of
  134. key/value pairs for the route variables. For the previous route, we would do:
  135. url, err := r.Get("article").URL("category", "technology", "id", "42")
  136. ...and the result will be a url.URL with the following path:
  137. "/articles/technology/42"
  138. This also works for host and query value variables:
  139. r := mux.NewRouter()
  140. r.Host("{subdomain}.domain.com").
  141. Path("/articles/{category}/{id:[0-9]+}").
  142. Queries("filter", "{filter}").
  143. HandlerFunc(ArticleHandler).
  144. Name("article")
  145. // url.String() will be "http://news.domain.com/articles/technology/42?filter=gorilla"
  146. url, err := r.Get("article").URL("subdomain", "news",
  147. "category", "technology",
  148. "id", "42",
  149. "filter", "gorilla")
  150. All variables defined in the route are required, and their values must
  151. conform to the corresponding patterns. These requirements guarantee that a
  152. generated URL will always match a registered route -- the only exception is
  153. for explicitly defined "build-only" routes which never match.
  154. Regex support also exists for matching Headers within a route. For example, we could do:
  155. r.HeadersRegexp("Content-Type", "application/(text|json)")
  156. ...and the route will match both requests with a Content-Type of `application/json` as well as
  157. `application/text`
  158. There's also a way to build only the URL host or path for a route:
  159. use the methods URLHost() or URLPath() instead. For the previous route,
  160. we would do:
  161. // "http://news.domain.com/"
  162. host, err := r.Get("article").URLHost("subdomain", "news")
  163. // "/articles/technology/42"
  164. path, err := r.Get("article").URLPath("category", "technology", "id", "42")
  165. And if you use subrouters, host and path defined separately can be built
  166. as well:
  167. r := mux.NewRouter()
  168. s := r.Host("{subdomain}.domain.com").Subrouter()
  169. s.Path("/articles/{category}/{id:[0-9]+}").
  170. HandlerFunc(ArticleHandler).
  171. Name("article")
  172. // "http://news.domain.com/articles/technology/42"
  173. url, err := r.Get("article").URL("subdomain", "news",
  174. "category", "technology",
  175. "id", "42")
  176. Mux supports the addition of middlewares to a Router, which are executed in the order they are added if a match is found, including its subrouters. Middlewares are (typically) small pieces of code which take one request, do something with it, and pass it down to another middleware or the final handler. Some common use cases for middleware are request logging, header manipulation, or ResponseWriter hijacking.
  177. type MiddlewareFunc func(http.Handler) http.Handler
  178. Typically, the returned handler is a closure which does something with the http.ResponseWriter and http.Request passed to it, and then calls the handler passed as parameter to the MiddlewareFunc (closures can access variables from the context where they are created).
  179. A very basic middleware which logs the URI of the request being handled could be written as:
  180. func simpleMw(next http.Handler) http.Handler {
  181. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  182. // Do stuff here
  183. log.Println(r.RequestURI)
  184. // Call the next handler, which can be another middleware in the chain, or the final handler.
  185. next.ServeHTTP(w, r)
  186. })
  187. }
  188. Middlewares can be added to a router using `Router.Use()`:
  189. r := mux.NewRouter()
  190. r.HandleFunc("/", handler)
  191. r.Use(simpleMw)
  192. A more complex authentication middleware, which maps session token to users, could be written as:
  193. // Define our struct
  194. type authenticationMiddleware struct {
  195. tokenUsers map[string]string
  196. }
  197. // Initialize it somewhere
  198. func (amw *authenticationMiddleware) Populate() {
  199. amw.tokenUsers["00000000"] = "user0"
  200. amw.tokenUsers["aaaaaaaa"] = "userA"
  201. amw.tokenUsers["05f717e5"] = "randomUser"
  202. amw.tokenUsers["deadbeef"] = "user0"
  203. }
  204. // Middleware function, which will be called for each request
  205. func (amw *authenticationMiddleware) Middleware(next http.Handler) http.Handler {
  206. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  207. token := r.Header.Get("X-Session-Token")
  208. if user, found := amw.tokenUsers[token]; found {
  209. // We found the token in our map
  210. log.Printf("Authenticated user %s\n", user)
  211. next.ServeHTTP(w, r)
  212. } else {
  213. http.Error(w, "Forbidden", http.StatusForbidden)
  214. }
  215. })
  216. }
  217. r := mux.NewRouter()
  218. r.HandleFunc("/", handler)
  219. amw := authenticationMiddleware{}
  220. amw.Populate()
  221. r.Use(amw.Middleware)
  222. Note: The handler chain will be stopped if your middleware doesn't call `next.ServeHTTP()` with the corresponding parameters. This can be used to abort a request if the middleware writer wants to.
  223. */
  224. package mux