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.
 
 
 

207 lines
7.0 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 and paths can have variables with an optional regular
  13. 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. The names are used to create a map of route variables which can be retrieved
  42. calling mux.Vars():
  43. vars := mux.Vars(request)
  44. category := vars["category"]
  45. And this is all you need to know about the basic usage. More advanced options
  46. are explained below.
  47. Routes can also be restricted to a domain or subdomain. Just define a host
  48. pattern to be matched. They can also have variables:
  49. r := mux.NewRouter()
  50. // Only matches if domain is "www.example.com".
  51. r.Host("www.example.com")
  52. // Matches a dynamic subdomain.
  53. r.Host("{subdomain:[a-z]+}.domain.com")
  54. There are several other matchers that can be added. To match path prefixes:
  55. r.PathPrefix("/products/")
  56. ...or HTTP methods:
  57. r.Methods("GET", "POST")
  58. ...or URL schemes:
  59. r.Schemes("https")
  60. ...or header values:
  61. r.Headers("X-Requested-With", "XMLHttpRequest")
  62. ...or query values:
  63. r.Queries("key", "value")
  64. ...or to use a custom matcher function:
  65. r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool {
  66. return r.ProtoMajor == 0
  67. })
  68. ...and finally, it is possible to combine several matchers in a single route:
  69. r.HandleFunc("/products", ProductsHandler).
  70. Host("www.example.com").
  71. Methods("GET").
  72. Schemes("http")
  73. Setting the same matching conditions again and again can be boring, so we have
  74. a way to group several routes that share the same requirements.
  75. We call it "subrouting".
  76. For example, let's say we have several URLs that should only match when the
  77. host is "www.example.com". Create a route for that host and get a "subrouter"
  78. from it:
  79. r := mux.NewRouter()
  80. s := r.Host("www.example.com").Subrouter()
  81. Then register routes in the subrouter:
  82. s.HandleFunc("/products/", ProductsHandler)
  83. s.HandleFunc("/products/{key}", ProductHandler)
  84. s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler)
  85. The three URL paths we registered above will only be tested if the domain is
  86. "www.example.com", because the subrouter is tested first. This is not
  87. only convenient, but also optimizes request matching. You can create
  88. subrouters combining any attribute matchers accepted by a route.
  89. Subrouters can be used to create domain or path "namespaces": you define
  90. subrouters in a central place and then parts of the app can register its
  91. paths relatively to a given subrouter.
  92. There's one more thing about subroutes. When a subrouter has a path prefix,
  93. the inner routes use it as base for their paths:
  94. r := mux.NewRouter()
  95. s := r.PathPrefix("/products").Subrouter()
  96. // "/products/"
  97. s.HandleFunc("/", ProductsHandler)
  98. // "/products/{key}/"
  99. s.HandleFunc("/{key}/", ProductHandler)
  100. // "/products/{key}/details"
  101. s.HandleFunc("/{key}/details", ProductDetailsHandler)
  102. Now let's see how to build registered URLs.
  103. Routes can be named. All routes that define a name can have their URLs built,
  104. or "reversed". We define a name calling Name() on a route. For example:
  105. r := mux.NewRouter()
  106. r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
  107. Name("article")
  108. To build a URL, get the route and call the URL() method, passing a sequence of
  109. key/value pairs for the route variables. For the previous route, we would do:
  110. url, err := r.Get("article").URL("category", "technology", "id", "42")
  111. ...and the result will be a url.URL with the following path:
  112. "/articles/technology/42"
  113. This also works for host variables:
  114. r := mux.NewRouter()
  115. r.Host("{subdomain}.domain.com").
  116. Path("/articles/{category}/{id:[0-9]+}").
  117. HandlerFunc(ArticleHandler).
  118. Name("article")
  119. // url.String() will be "http://news.domain.com/articles/technology/42"
  120. url, err := r.Get("article").URL("subdomain", "news",
  121. "category", "technology",
  122. "id", "42")
  123. All variables defined in the route are required, and their values must
  124. conform to the corresponding patterns. These requirements guarantee that a
  125. generated URL will always match a registered route -- the only exception is
  126. for explicitly defined "build-only" routes which never match.
  127. Regex support also exists for matching Headers within a route. For example, we could do:
  128. r.HeadersRegexp("Content-Type", "application/(text|json)")
  129. ...and the route will match both requests with a Content-Type of `application/json` as well as
  130. `application/text`
  131. There's also a way to build only the URL host or path for a route:
  132. use the methods URLHost() or URLPath() instead. For the previous route,
  133. we would do:
  134. // "http://news.domain.com/"
  135. host, err := r.Get("article").URLHost("subdomain", "news")
  136. // "/articles/technology/42"
  137. path, err := r.Get("article").URLPath("category", "technology", "id", "42")
  138. And if you use subrouters, host and path defined separately can be built
  139. as well:
  140. r := mux.NewRouter()
  141. s := r.Host("{subdomain}.domain.com").Subrouter()
  142. s.Path("/articles/{category}/{id:[0-9]+}").
  143. HandlerFunc(ArticleHandler).
  144. Name("article")
  145. // "http://news.domain.com/articles/technology/42"
  146. url, err := r.Get("article").URL("subdomain", "news",
  147. "category", "technology",
  148. "id", "42")
  149. */
  150. package mux