doc.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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 gorilla/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.domain.com".
  51. r.Host("www.domain.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.domain.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.domain.com". Create a route for that host and get a "subrouter"
  78. from it:
  79. r := mux.NewRouter()
  80. s := r.Host("www.domain.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.domain.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. There's also a way to build only the URL host or path for a route:
  128. use the methods URLHost() or URLPath() instead. For the previous route,
  129. we would do:
  130. // "http://news.domain.com/"
  131. host, err := r.Get("article").URLHost("subdomain", "news")
  132. // "/articles/technology/42"
  133. path, err := r.Get("article").URLPath("category", "technology", "id", "42")
  134. And if you use subrouters, host and path defined separately can be built
  135. as well:
  136. r := mux.NewRouter()
  137. s := r.Host("{subdomain}.domain.com").Subrouter()
  138. s.Path("/articles/{category}/{id:[0-9]+}").
  139. HandlerFunc(ArticleHandler).
  140. Name("article")
  141. // "http://news.domain.com/articles/technology/42"
  142. url, err := r.Get("article").URL("subdomain", "news",
  143. "category", "technology",
  144. "id", "42")
  145. */
  146. package mux