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)
6 http://www.gorillatoolkit.org/pkg/mux
8 Package `gorilla/mux` implements a request router and dispatcher.
10 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:
12 * Requests can be matched based on URL host, path, path prefix, schemes, header and query values, HTTP methods or using custom matchers.
13 * URL hosts and paths can have variables with an optional regular expression.
14 * Registered URLs can be built, or "reversed", which helps maintaining references to resources.
15 * 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.
16 * It implements the `http.Handler` interface so it is compatible with the standard `http.ServeMux`.
18 Let's start registering a couple of URL paths and handlers:
23 r.HandleFunc("/", HomeHandler)
24 r.HandleFunc("/products", ProductsHandler)
25 r.HandleFunc("/articles", ArticlesHandler)
30 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.
32 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:
36 r.HandleFunc("/products/{key}", ProductHandler)
37 r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler)
38 r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
41 The names are used to create a map of route variables which can be retrieved calling `mux.Vars()`:
44 vars := mux.Vars(request)
45 category := vars["category"]
48 And this is all you need to know about the basic usage. More advanced options are explained below.
50 Routes can also be restricted to a domain or subdomain. Just define a host pattern to be matched. They can also have variables:
54 // Only matches if domain is "www.example.com".
55 r.Host("www.example.com")
56 // Matches a dynamic subdomain.
57 r.Host("{subdomain:[a-z]+}.domain.com")
60 There are several other matchers that can be added. To match path prefixes:
63 r.PathPrefix("/products/")
69 r.Methods("GET", "POST")
81 r.Headers("X-Requested-With", "XMLHttpRequest")
87 r.Queries("key", "value")
90 ...or to use a custom matcher function:
93 r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool {
94 return r.ProtoMajor == 0
98 ...and finally, it is possible to combine several matchers in a single route:
101 r.HandleFunc("/products", ProductsHandler).
102 Host("www.example.com").
107 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".
109 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:
113 s := r.Host("www.example.com").Subrouter()
116 Then register routes in the subrouter:
119 s.HandleFunc("/products/", ProductsHandler)
120 s.HandleFunc("/products/{key}", ProductHandler)
121 s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler)
124 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.
126 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.
128 There's one more thing about subroutes. When a subrouter has a path prefix, the inner routes use it as base for their paths:
132 s := r.PathPrefix("/products").Subrouter()
134 s.HandleFunc("/", ProductsHandler)
135 // "/products/{key}/"
136 s.HandleFunc("/{key}/", ProductHandler)
137 // "/products/{key}/details"
138 s.HandleFunc("/{key}/details", ProductDetailsHandler)
141 Now let's see how to build registered URLs.
143 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:
147 r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
151 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:
154 url, err := r.Get("article").URL("category", "technology", "id", "42")
157 ...and the result will be a `url.URL` with the following path:
160 "/articles/technology/42"
163 This also works for host variables:
167 r.Host("{subdomain}.domain.com").
168 Path("/articles/{category}/{id:[0-9]+}").
169 HandlerFunc(ArticleHandler).
172 // url.String() will be "http://news.domain.com/articles/technology/42"
173 url, err := r.Get("article").URL("subdomain", "news",
174 "category", "technology",
178 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.
180 Regex support also exists for matching Headers within a route. For example, we could do:
183 r.HeadersRegexp("Content-Type", "application/(text|json)")
186 ...and the route will match both requests with a Content-Type of `application/json` as well as `application/text`
188 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:
191 // "http://news.domain.com/"
192 host, err := r.Get("article").URLHost("subdomain", "news")
194 // "/articles/technology/42"
195 path, err := r.Get("article").URLPath("category", "technology", "id", "42")
198 And if you use subrouters, host and path defined separately can be built as well:
202 s := r.Host("{subdomain}.domain.com").Subrouter()
203 s.Path("/articles/{category}/{id:[0-9]+}").
204 HandlerFunc(ArticleHandler).
207 // "http://news.domain.com/articles/technology/42"
208 url, err := r.Get("article").URL("subdomain", "news",
209 "category", "technology",
215 Here's a complete, runnable example of a small `mux` based server:
223 "github.com/gorilla/mux"
226 func YourHandler(w http.ResponseWriter, r *http.Request) {
227 w.Write([]byte("Gorilla!\n"))
232 // Routes consist of a path and a handler function.
233 r.HandleFunc("/", YourHandler)
235 // Bind to a port and pass our router in
236 http.ListenAndServe(":8000", r)
242 BSD licensed. See the LICENSE file for details.