var ( // ErrMethodMismatch is returned when the method in the request does not match // the method defined against the route. ErrMethodMismatch = errors.New("method is not allowed") // ErrNotFound is returned when no route match is found. ErrNotFound = errors.New("no matching route was found") )
SkipRouter is used as a return value from WalkFuncs to indicate that the router that walk is about to descend down to should be skipped.
var SkipRouter = errors.New("skip this router")
func SetURLVars(r *http.Request, val map[string]string) *http.Request
SetURLVars sets the URL variables for the given request, to be accessed via mux.Vars for testing route behaviour. Arguments are not modified, a shallow copy is returned.
This API should only be used for testing purposes; it provides a way to inject variables into the request context. Alternatively, URL variables can be set by making a route that captures the required variables, starting a server and sending the request to that server.
▹ Example
func Vars(r *http.Request) map[string]string
Vars returns the route variables for the current request, if any.
BuildVarsFunc is the function signature used by custom build variable functions (which can modify route variables before a route's URL is built).
type BuildVarsFunc func(map[string]string) map[string]string
MatcherFunc is the function signature used by custom matchers.
type MatcherFunc func(*http.Request, *RouteMatch) bool
func (m MatcherFunc) Match(r *http.Request, match *RouteMatch) bool
Match returns the match for a given request.
MiddlewareFunc is a function which receives an http.Handler and returns another http.Handler. 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.
type MiddlewareFunc func(http.Handler) http.Handler
func CORSMethodMiddleware(r *Router) MiddlewareFunc
CORSMethodMiddleware automatically sets the Access-Control-Allow-Methods response header on requests for routes that have an OPTIONS method matcher to all the method matchers on the route. Routes that do not explicitly handle OPTIONS requests will not be processed by the middleware. See examples for usage.
▹ Example
func (mw MiddlewareFunc) Middleware(handler http.Handler) http.Handler
Middleware allows MiddlewareFunc to implement the middleware interface.
Route stores information to match a request and build URLs.
type Route struct {
// contains filtered or unexported fields
}
func CurrentRoute(r *http.Request) *Route
CurrentRoute returns the matched route for the current request, if any. This only works when called inside the handler of the matched route because the matched route is stored in the request context which is cleared after the handler returns.
func (r *Route) BuildOnly() *Route
BuildOnly sets the route to never match: it is only used to build URLs.
func (r *Route) BuildVarsFunc(f BuildVarsFunc) *Route
BuildVarsFunc adds a custom function to be used to modify build variables before a route's URL is built.
func (r *Route) GetError() error
GetError returns an error resulted from building the route, if any.
func (r *Route) GetHandler() http.Handler
GetHandler returns the handler for the route, if any.
func (r *Route) GetHostTemplate() (string, error)
GetHostTemplate returns the template used to build the route match. This is useful for building simple REST API documentation and for instrumentation against third-party services. An error will be returned if the route does not define a host.
func (r *Route) GetMethods() ([]string, error)
GetMethods returns the methods the route matches against This is useful for building simple REST API documentation and for instrumentation against third-party services. An error will be returned if route does not have methods.
func (r *Route) GetName() string
GetName returns the name for the route, if any.
func (r *Route) GetPathRegexp() (string, error)
GetPathRegexp returns the expanded regular expression used to match route path. This is useful for building simple REST API documentation and for instrumentation against third-party services. An error will be returned if the route does not define a path.
func (r *Route) GetPathTemplate() (string, error)
GetPathTemplate returns the template used to build the route match. This is useful for building simple REST API documentation and for instrumentation against third-party services. An error will be returned if the route does not define a path.
func (r *Route) GetQueriesRegexp() ([]string, error)
GetQueriesRegexp returns the expanded regular expressions used to match the route queries. This is useful for building simple REST API documentation and for instrumentation against third-party services. An error will be returned if the route does not have queries.
func (r *Route) GetQueriesTemplates() ([]string, error)
GetQueriesTemplates returns the templates used to build the query matching. This is useful for building simple REST API documentation and for instrumentation against third-party services. An error will be returned if the route does not define queries.
func (r *Route) GetVarNames() ([]string, error)
GetVarNames returns the names of all variables added by regexp matchers These can be used to know which route variables should be passed into r.URL()
▹ Example
func (r *Route) Handler(handler http.Handler) *Route
Handler sets a handler for the route.
func (r *Route) HandlerFunc(f func(http.ResponseWriter, *http.Request)) *Route
HandlerFunc sets a handler function for the route.
func (r *Route) Headers(pairs ...string) *Route
Headers adds a matcher for request header values. It accepts a sequence of key/value pairs to be matched. For example:
r := mux.NewRouter().NewRoute() r.Headers("Content-Type", "application/json", "X-Requested-With", "XMLHttpRequest")
The above route will only match if both request header values match. If the value is an empty string, it will match any value if the key is set.
func (r *Route) HeadersRegexp(pairs ...string) *Route
HeadersRegexp accepts a sequence of key/value pairs, where the value has regex support. For example:
r := mux.NewRouter().NewRoute() r.HeadersRegexp("Content-Type", "application/(text|json)", "X-Requested-With", "XMLHttpRequest")
The above route will only match if both the request header matches both regular expressions. If the value is an empty string, it will match any value if the key is set. Use the start and end of string anchors (^ and $) to match an exact value.
▹ Example
▹ Example (ExactMatch)
func (r *Route) Host(tpl string) *Route
Host adds a matcher for the URL host. It accepts a template with zero or more URL variables enclosed by {}. Variables can define an optional regexp pattern to be matched:
- {name} matches anything until the next dot.
- {name:pattern} matches the given regexp pattern.
For example:
r := mux.NewRouter().NewRoute() r.Host("www.example.com") r.Host("{subdomain}.domain.com") r.Host("{subdomain:[a-z]+}.domain.com")
Variable names must be unique in a given route. They can be retrieved calling mux.Vars(request).
func (r *Route) Match(req *http.Request, match *RouteMatch) bool
Match matches the route against the request.
func (r *Route) MatcherFunc(f MatcherFunc) *Route
MatcherFunc adds a custom function to be used as request matcher.
func (r *Route) Methods(methods ...string) *Route
Methods adds a matcher for HTTP methods. It accepts a sequence of one or more methods to be matched, e.g.: "GET", "POST", "PUT".
func (r *Route) Name(name string) *Route
Name sets the name for the route, used to build URLs. It is an error to call Name more than once on a route.
func (r *Route) Path(tpl string) *Route
Path adds a matcher for the URL path. It accepts a template with zero or more URL variables enclosed by {}. The template must start with a "/". Variables can define an optional regexp pattern to be matched:
- {name} matches anything until the next slash.
- {name:pattern} matches the given regexp pattern.
For example:
r := mux.NewRouter().NewRoute() r.Path("/products/").Handler(ProductsHandler) r.Path("/products/{key}").Handler(ProductsHandler) r.Path("/articles/{category}/{id:[0-9]+}"). Handler(ArticleHandler)
Variable names must be unique in a given route. They can be retrieved calling mux.Vars(request).
func (r *Route) PathPrefix(tpl string) *Route
PathPrefix adds a matcher for the URL path prefix. This matches if the given template is a prefix of the full URL path. See Route.Path() for details on the tpl argument.
Note that it does not treat slashes specially ("/foobar/" will be matched by the prefix "/foo") so you may want to use a trailing slash here.
Also note that the setting of Router.StrictSlash() has no effect on routes with a PathPrefix matcher.
func (r *Route) Queries(pairs ...string) *Route
Queries adds a matcher for URL query values. It accepts a sequence of key/value pairs. Values may define variables. For example:
r := mux.NewRouter().NewRoute() r.Queries("foo", "bar", "id", "{id:[0-9]+}")
The above route will only match if the URL contains the defined queries values, e.g.: ?foo=bar&id=42.
If the value is an empty string, it will match any value if the key is set.
Variables can define an optional regexp pattern to be matched:
- {name} matches anything until the next slash.
- {name:pattern} matches the given regexp pattern.
func (r *Route) Schemes(schemes ...string) *Route
Schemes adds a matcher for URL schemes. It accepts a sequence of schemes to be matched, e.g.: "http", "https". If the request's URL has a scheme set, it will be matched against. Generally, the URL scheme will only be set if a previous handler set it, such as the ProxyHeaders handler from gorilla/handlers. If unset, the scheme will be determined based on the request's TLS termination state. The first argument to Schemes will be used when constructing a route URL.
func (r *Route) SkipClean() bool
SkipClean reports whether path cleaning is enabled for this route via Router.SkipClean.
func (r *Route) Subrouter() *Router
Subrouter creates a subrouter for the route.
It will test the inner routes only if the parent route matched. For example:
r := mux.NewRouter().NewRoute() s := r.Host("www.example.com").Subrouter() s.HandleFunc("/products/", ProductsHandler) s.HandleFunc("/products/{key}", ProductHandler) s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler)
Here, the routes registered in the subrouter won't be tested if the host doesn't match.
func (r *Route) URL(pairs ...string) (*url.URL, error)
URL builds a URL for the route.
It accepts a sequence of key/value pairs for the route variables. For example, given this route:
r := mux.NewRouter() r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). Name("article")
...a URL for it can be built using:
url, err := r.Get("article").URL("category", "technology", "id", "42")
...which will return an url.URL with the following path:
"/articles/technology/42"
This also works for host variables:
r := mux.NewRouter() r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). Host("{subdomain}.domain.com"). Name("article") // url.String() will be "http://news.domain.com/articles/technology/42" url, err := r.Get("article").URL("subdomain", "news", "category", "technology", "id", "42")
The scheme of the resulting url will be the first argument that was passed to Schemes:
// url.String() will be "https://example.com" r := mux.NewRouter().NewRoute() url, err := r.Host("example.com") .Schemes("https", "http").URL()
All variables defined in the route are required, and their values must conform to the corresponding patterns.
func (r *Route) URLHost(pairs ...string) (*url.URL, error)
URLHost builds the host part of the URL for a route. See Route.URL().
The route must have a host defined.
func (r *Route) URLPath(pairs ...string) (*url.URL, error)
URLPath builds the path part of the URL for a route. See Route.URL().
The route must have a path defined.
RouteMatch stores information about a matched route.
type RouteMatch struct { Route *Route Handler http.Handler Vars map[string]string // MatchErr is set to appropriate matching error // It is set to ErrMethodMismatch if there is a mismatch in // the request method and route method MatchErr error }
Router registers routes to be matched and dispatches a handler.
It implements the http.Handler interface, so it can be registered to serve requests:
var router = mux.NewRouter() func main() { http.Handle("/", router) }
Or, for Google App Engine, register it in a init() function:
func init() { http.Handle("/", router) }
This will send all incoming requests to the router.
type Router struct { // Configurable Handler to be used when no route matches. // This can be used to render your own 404 Not Found errors. NotFoundHandler http.Handler // Configurable Handler to be used when the request method does not match the route. // This can be used to render your own 405 Method Not Allowed errors. MethodNotAllowedHandler http.Handler // If true, do not clear the request context after handling the request. // // Deprecated: No effect, since the context is stored on the request itself. KeepContext bool // contains filtered or unexported fields }
func NewRouter() *Router
NewRouter returns a new router instance.
func (r *Router) BuildVarsFunc(f BuildVarsFunc) *Route
BuildVarsFunc registers a new route with a custom function for modifying route variables before building a URL.
func (r *Router) Get(name string) *Route
Get returns a route registered with the given name.
func (r *Router) GetRoute(name string) *Route
GetRoute returns a route registered with the given name. This method was renamed to Get() and remains here for backwards compatibility.
func (r *Router) Handle(path string, handler http.Handler) *Route
Handle registers a new route with a matcher for the URL path. See Route.Path() and Route.Handler().
func (r *Router) HandleFunc(path string, f func(http.ResponseWriter, *http.Request)) *Route
HandleFunc registers a new route with a matcher for the URL path. See Route.Path() and Route.HandlerFunc().
func (r *Router) Headers(pairs ...string) *Route
Headers registers a new route with a matcher for request header values. See Route.Headers().
func (r *Router) Host(tpl string) *Route
Host registers a new route with a matcher for the URL host. See Route.Host().
func (r *Router) Match(req *http.Request, match *RouteMatch) bool
Match attempts to match the given request against the router's registered routes.
If the request matches a route of this router or one of its subrouters the Route, Handler, and Vars fields of the the match argument are filled and this function returns true.
If the request does not match any of this router's or its subrouters' routes then this function returns false. If available, a reason for the match failure will be filled in the match argument's MatchErr field. If the match failure type (eg: not found) has a registered handler, the handler is assigned to the Handler field of the match argument.
func (r *Router) MatcherFunc(f MatcherFunc) *Route
MatcherFunc registers a new route with a custom matcher function. See Route.MatcherFunc().
func (r *Router) Methods(methods ...string) *Route
Methods registers a new route with a matcher for HTTP methods. See Route.Methods().
func (r *Router) Name(name string) *Route
Name registers a new route with a name. See Route.Name().
func (r *Router) NewRoute() *Route
NewRoute registers an empty route.
func (r *Router) Path(tpl string) *Route
Path registers a new route with a matcher for the URL path. See Route.Path().
func (r *Router) PathPrefix(tpl string) *Route
PathPrefix registers a new route with a matcher for the URL path prefix. See Route.PathPrefix().
func (r *Router) Queries(pairs ...string) *Route
Queries registers a new route with a matcher for URL query values. See Route.Queries().
func (r *Router) Schemes(schemes ...string) *Route
Schemes registers a new route with a matcher for URL schemes. See Route.Schemes().
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
ServeHTTP dispatches the handler registered in the matched route.
When there is a match, the route variables can be retrieved calling mux.Vars(request).
func (r *Router) SkipClean(value bool) *Router
SkipClean defines the path cleaning behaviour for new routes. The initial value is false. Users should be careful about which routes are not cleaned
When true, if the route path is "/path//to", it will remain with the double slash. This is helpful if you have a route like: /fetch/http://xkcd.com/534/
When false, the path will be cleaned, so /fetch/http://xkcd.com/534/ will become /fetch/http/xkcd.com/534
func (r *Router) StrictSlash(value bool) *Router
StrictSlash defines the trailing slash behavior for new routes. The initial value is false.
When true, if the route path is "/path/", accessing "/path" will perform a redirect to the former and vice versa. In other words, your application will always see the path as specified in the route.
When false, if the route path is "/path", accessing "/path/" will not match this route and vice versa.
The re-direct is a HTTP 301 (Moved Permanently). Note that when this is set for routes with a non-idempotent method (e.g. POST, PUT), the subsequent re-directed request will be made as a GET by most clients. Use middleware or client settings to modify this behaviour as needed.
Special case: when a route sets a path prefix using the PathPrefix() method, strict slash is ignored for that route because the redirect behavior can't be determined from a prefix alone. However, any subrouters created from that route inherit the original StrictSlash setting.
func (r *Router) Use(mwf ...MiddlewareFunc)
Use appends a MiddlewareFunc to the chain. Middleware can be used to intercept or otherwise modify requests and/or responses, and are executed in the order that they are applied to the Router.
func (r *Router) UseEncodedPath() *Router
UseEncodedPath tells the router to match the encoded original path to the routes. For eg. "/path/foo%2Fbar/to" will match the path "/path/{var}/to".
If not called, the router will match the unencoded path to the routes. For eg. "/path/foo%2Fbar/to" will match the path "/path/foo/bar/to"
func (r *Router) Walk(walkFn WalkFunc) error
Walk walks the router and all its sub-routers, calling walkFn for each route in the tree. The routes are walked in the order they were added. Sub-routers are explored depth-first.
WalkFunc is the type of the function called for each route visited by Walk. At every invocation, it is given the current route, and the current router, and a list of ancestor routes that lead to the current route.
type WalkFunc func(route *Route, router *Router, ancestors []*Route) error