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.

README.md 10 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. gorilla/mux
  2. ===
  3. [![GoDoc](https://godoc.org/github.com/gorilla/mux?status.svg)](https://godoc.org/github.com/gorilla/mux)
  4. [![Build Status](https://travis-ci.org/gorilla/mux.svg?branch=master)](https://travis-ci.org/gorilla/mux)
  5. ![Gorilla Logo](http://www.gorillatoolkit.org/static/images/gorilla-icon-64.png)
  6. http://www.gorillatoolkit.org/pkg/mux
  7. Package `gorilla/mux` implements a request router and dispatcher for matching incoming requests to
  8. their respective handler.
  9. The name mux stands for "HTTP request multiplexer". Like the standard `http.ServeMux`, `mux.Router` matches incoming requests against a list of registered routes and calls a handler for the route that matches the URL or other conditions. The main features are:
  10. * It implements the `http.Handler` interface so it is compatible with the standard `http.ServeMux`.
  11. * Requests can be matched based on URL host, path, path prefix, schemes, header and query values, HTTP methods or using custom matchers.
  12. * URL hosts and paths can have variables with an optional regular expression.
  13. * Registered URLs can be built, or "reversed", which helps maintaining references to resources.
  14. * Routes can be used as subrouters: nested routes are only tested if the parent route matches. This is useful to define groups of routes that share common conditions like a host, a path prefix or other repeated attributes. As a bonus, this optimizes request matching.
  15. ---
  16. * [Install](#install)
  17. * [Examples](#examples)
  18. * [Matching Routes](#matching-routes)
  19. * [Listing Routes](#listing-routes)
  20. * [Static Files](#static-files)
  21. * [Registered URLs](#registered-urls)
  22. * [Full Example](#full-example)
  23. ---
  24. ## Install
  25. With a [correctly configured](https://golang.org/doc/install#testing) Go toolchain:
  26. ```sh
  27. go get -u github.com/gorilla/mux
  28. ```
  29. ## Examples
  30. Let's start registering a couple of URL paths and handlers:
  31. ```go
  32. func main() {
  33. r := mux.NewRouter()
  34. r.HandleFunc("/", HomeHandler)
  35. r.HandleFunc("/products", ProductsHandler)
  36. r.HandleFunc("/articles", ArticlesHandler)
  37. http.Handle("/", r)
  38. }
  39. ```
  40. Here we register three routes mapping URL paths to handlers. This is equivalent to how `http.HandleFunc()` works: if an incoming request URL matches one of the paths, the corresponding handler is called passing (`http.ResponseWriter`, `*http.Request`) as parameters.
  41. Paths can have variables. They are defined using the format `{name}` or `{name:pattern}`. If a regular expression pattern is not defined, the matched variable will be anything until the next slash. For example:
  42. ```go
  43. r := mux.NewRouter()
  44. r.HandleFunc("/products/{key}", ProductHandler)
  45. r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler)
  46. r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
  47. ```
  48. The names are used to create a map of route variables which can be retrieved calling `mux.Vars()`:
  49. ```go
  50. func ArticlesCategoryHandler(w http.ResponseWriter, r *http.Request) {
  51. vars := mux.Vars(r)
  52. w.WriteHeader(http.StatusOK)
  53. fmt.Fprintf(w, "Category: %v\n", vars["category"])
  54. }
  55. ```
  56. And this is all you need to know about the basic usage. More advanced options are explained below.
  57. ### Matching Routes
  58. Routes can also be restricted to a domain or subdomain. Just define a host pattern to be matched. They can also have variables:
  59. ```go
  60. r := mux.NewRouter()
  61. // Only matches if domain is "www.example.com".
  62. r.Host("www.example.com")
  63. // Matches a dynamic subdomain.
  64. r.Host("{subdomain:[a-z]+}.domain.com")
  65. ```
  66. There are several other matchers that can be added. To match path prefixes:
  67. ```go
  68. r.PathPrefix("/products/")
  69. ```
  70. ...or HTTP methods:
  71. ```go
  72. r.Methods("GET", "POST")
  73. ```
  74. ...or URL schemes:
  75. ```go
  76. r.Schemes("https")
  77. ```
  78. ...or header values:
  79. ```go
  80. r.Headers("X-Requested-With", "XMLHttpRequest")
  81. ```
  82. ...or query values:
  83. ```go
  84. r.Queries("key", "value")
  85. ```
  86. ...or to use a custom matcher function:
  87. ```go
  88. r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool {
  89. return r.ProtoMajor == 0
  90. })
  91. ```
  92. ...and finally, it is possible to combine several matchers in a single route:
  93. ```go
  94. r.HandleFunc("/products", ProductsHandler).
  95. Host("www.example.com").
  96. Methods("GET").
  97. Schemes("http")
  98. ```
  99. Setting the same matching conditions again and again can be boring, so we have a way to group several routes that share the same requirements. We call it "subrouting".
  100. For example, let's say we have several URLs that should only match when the host is `www.example.com`. Create a route for that host and get a "subrouter" from it:
  101. ```go
  102. r := mux.NewRouter()
  103. s := r.Host("www.example.com").Subrouter()
  104. ```
  105. Then register routes in the subrouter:
  106. ```go
  107. s.HandleFunc("/products/", ProductsHandler)
  108. s.HandleFunc("/products/{key}", ProductHandler)
  109. s.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
  110. ```
  111. The three URL paths we registered above will only be tested if the domain is `www.example.com`, because the subrouter is tested first. This is not only convenient, but also optimizes request matching. You can create subrouters combining any attribute matchers accepted by a route.
  112. Subrouters can be used to create domain or path "namespaces": you define subrouters in a central place and then parts of the app can register its paths relatively to a given subrouter.
  113. There's one more thing about subroutes. When a subrouter has a path prefix, the inner routes use it as base for their paths:
  114. ```go
  115. r := mux.NewRouter()
  116. s := r.PathPrefix("/products").Subrouter()
  117. // "/products/"
  118. s.HandleFunc("/", ProductsHandler)
  119. // "/products/{key}/"
  120. s.HandleFunc("/{key}/", ProductHandler)
  121. // "/products/{key}/details"
  122. s.HandleFunc("/{key}/details", ProductDetailsHandler)
  123. ```
  124. ### Listing Routes
  125. Routes on a mux can be listed using the Router.Walk method—useful for generating documentation:
  126. ```go
  127. package main
  128. import (
  129. "fmt"
  130. "net/http"
  131. "github.com/gorilla/mux"
  132. )
  133. func handler(w http.ResponseWriter, r *http.Request) {
  134. return
  135. }
  136. func main() {
  137. r := mux.NewRouter()
  138. r.HandleFunc("/", handler)
  139. r.HandleFunc("/products", handler)
  140. r.HandleFunc("/articles", handler)
  141. r.HandleFunc("/articles/{id}", handler)
  142. r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
  143. t, err := route.GetPathTemplate()
  144. if err != nil {
  145. return err
  146. }
  147. fmt.Println(t)
  148. return nil
  149. })
  150. http.Handle("/", r)
  151. }
  152. ```
  153. ### Static Files
  154. Note that the path provided to `PathPrefix()` represents a "wildcard": calling
  155. `PathPrefix("/static/").Handler(...)` means that the handler will be passed any
  156. request that matches "/static/*". This makes it easy to serve static files with mux:
  157. ```go
  158. func main() {
  159. var dir string
  160. flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir")
  161. flag.Parse()
  162. r := mux.NewRouter()
  163. // This will serve files under http://localhost:8000/static/<filename>
  164. r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir))))
  165. srv := &http.Server{
  166. Handler: r,
  167. Addr: "127.0.0.1:8000",
  168. // Good practice: enforce timeouts for servers you create!
  169. WriteTimeout: 15 * time.Second,
  170. ReadTimeout: 15 * time.Second,
  171. }
  172. log.Fatal(srv.ListenAndServe())
  173. }
  174. ```
  175. ### Registered URLs
  176. Now let's see how to build registered URLs.
  177. Routes can be named. All routes that define a name can have their URLs built, or "reversed". We define a name calling `Name()` on a route. For example:
  178. ```go
  179. r := mux.NewRouter()
  180. r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
  181. Name("article")
  182. ```
  183. To build a URL, get the route and call the `URL()` method, passing a sequence of key/value pairs for the route variables. For the previous route, we would do:
  184. ```go
  185. url, err := r.Get("article").URL("category", "technology", "id", "42")
  186. ```
  187. ...and the result will be a `url.URL` with the following path:
  188. ```
  189. "/articles/technology/42"
  190. ```
  191. This also works for host variables:
  192. ```go
  193. r := mux.NewRouter()
  194. r.Host("{subdomain}.domain.com").
  195. Path("/articles/{category}/{id:[0-9]+}").
  196. HandlerFunc(ArticleHandler).
  197. Name("article")
  198. // url.String() will be "http://news.domain.com/articles/technology/42"
  199. url, err := r.Get("article").URL("subdomain", "news",
  200. "category", "technology",
  201. "id", "42")
  202. ```
  203. All variables defined in the route are required, and their values must conform to the corresponding patterns. These requirements guarantee that a generated URL will always match a registered route -- the only exception is for explicitly defined "build-only" routes which never match.
  204. Regex support also exists for matching Headers within a route. For example, we could do:
  205. ```go
  206. r.HeadersRegexp("Content-Type", "application/(text|json)")
  207. ```
  208. ...and the route will match both requests with a Content-Type of `application/json` as well as `application/text`
  209. There's also a way to build only the URL host or path for a route: use the methods `URLHost()` or `URLPath()` instead. For the previous route, we would do:
  210. ```go
  211. // "http://news.domain.com/"
  212. host, err := r.Get("article").URLHost("subdomain", "news")
  213. // "/articles/technology/42"
  214. path, err := r.Get("article").URLPath("category", "technology", "id", "42")
  215. ```
  216. And if you use subrouters, host and path defined separately can be built as well:
  217. ```go
  218. r := mux.NewRouter()
  219. s := r.Host("{subdomain}.domain.com").Subrouter()
  220. s.Path("/articles/{category}/{id:[0-9]+}").
  221. HandlerFunc(ArticleHandler).
  222. Name("article")
  223. // "http://news.domain.com/articles/technology/42"
  224. url, err := r.Get("article").URL("subdomain", "news",
  225. "category", "technology",
  226. "id", "42")
  227. ```
  228. ## Full Example
  229. Here's a complete, runnable example of a small `mux` based server:
  230. ```go
  231. package main
  232. import (
  233. "net/http"
  234. "log"
  235. "github.com/gorilla/mux"
  236. )
  237. func YourHandler(w http.ResponseWriter, r *http.Request) {
  238. w.Write([]byte("Gorilla!\n"))
  239. }
  240. func main() {
  241. r := mux.NewRouter()
  242. // Routes consist of a path and a handler function.
  243. r.HandleFunc("/", YourHandler)
  244. // Bind to a port and pass our router in
  245. log.Fatal(http.ListenAndServe(":8000", r))
  246. }
  247. ```
  248. ## License
  249. BSD licensed. See the LICENSE file for details.