mux

package
v0.13.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2015 License: BSD-3-Clause, Apache-2.0 Imports: 9 Imported by: 0

README

mux

Build Status

gorilla/mux is a powerful URL router and dispatcher.

Read the full documentation here: http://www.gorillatoolkit.org/pkg/mux

Documentation

Overview

Package gorilla/mux implements a request router and dispatcher.

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:

  • Requests can be matched based on URL host, path, path prefix, schemes, header and query values, HTTP methods or using custom matchers.
  • URL hosts and paths can have variables with an optional regular expression.
  • Registered URLs can be built, or "reversed", which helps maintaining references to resources.
  • 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.
  • It implements the http.Handler interface so it is compatible with the standard http.ServeMux.

Let's start registering a couple of URL paths and handlers:

func main() {
	r := mux.NewRouter()
	r.HandleFunc("/", HomeHandler)
	r.HandleFunc("/products", ProductsHandler)
	r.HandleFunc("/articles", ArticlesHandler)
	http.Handle("/", r)
}

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.

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:

r := mux.NewRouter()
r.HandleFunc("/products/{key}", ProductHandler)
r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler)
r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)

The names are used to create a map of route variables which can be retrieved calling mux.Vars():

vars := mux.Vars(request)
category := vars["category"]

And this is all you need to know about the basic usage. More advanced options are explained below.

Routes can also be restricted to a domain or subdomain. Just define a host pattern to be matched. They can also have variables:

r := mux.NewRouter()
// Only matches if domain is "www.domain.com".
r.Host("www.domain.com")
// Matches a dynamic subdomain.
r.Host("{subdomain:[a-z]+}.domain.com")

There are several other matchers that can be added. To match path prefixes:

r.PathPrefix("/products/")

...or HTTP methods:

r.Methods("GET", "POST")

...or URL schemes:

r.Schemes("https")

...or header values:

r.Headers("X-Requested-With", "XMLHttpRequest")

...or query values:

r.Queries("key", "value")

...or to use a custom matcher function:

	r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool {
		return r.ProtoMajor == 0
    })

...and finally, it is possible to combine several matchers in a single route:

r.HandleFunc("/products", ProductsHandler).
  Host("www.domain.com").
  Methods("GET").
  Schemes("http")

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".

For example, let's say we have several URLs that should only match when the host is "www.domain.com". Create a route for that host and get a "subrouter" from it:

r := mux.NewRouter()
s := r.Host("www.domain.com").Subrouter()

Then register routes in the subrouter:

s.HandleFunc("/products/", ProductsHandler)
s.HandleFunc("/products/{key}", ProductHandler)
s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler)

The three URL paths we registered above will only be tested if the domain is "www.domain.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.

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.

There's one more thing about subroutes. When a subrouter has a path prefix, the inner routes use it as base for their paths:

r := mux.NewRouter()
s := r.PathPrefix("/products").Subrouter()
// "/products/"
s.HandleFunc("/", ProductsHandler)
// "/products/{key}/"
s.HandleFunc("/{key}/", ProductHandler)
// "/products/{key}/details"
s.HandleFunc("/{key}/details", ProductDetailsHandler)

Now let's see how to build registered URLs.

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:

r := mux.NewRouter()
r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
  Name("article")

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:

url, err := r.Get("article").URL("category", "technology", "id", "42")

...and the result will be a url.URL with the following path:

"/articles/technology/42"

This also works for host variables:

r := mux.NewRouter()
r.Host("{subdomain}.domain.com").
  Path("/articles/{category}/{id:[0-9]+}").
  HandlerFunc(ArticleHandler).
  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")

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.

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:

// "http://news.domain.com/"
host, err := r.Get("article").URLHost("subdomain", "news")

// "/articles/technology/42"
path, err := r.Get("article").URLPath("category", "technology", "id", "42")

And if you use subrouters, host and path defined separately can be built as well:

r := mux.NewRouter()
s := r.Host("{subdomain}.domain.com").Subrouter()
s.Path("/articles/{category}/{id:[0-9]+}").
  HandlerFunc(ArticleHandler).
  Name("article")

// "http://news.domain.com/articles/technology/42"
url, err := r.Get("article").URL("subdomain", "news",
								 "category", "technology",
								 "id", "42")

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Vars

func Vars(r *http.Request) map[string]string

Vars returns the route variables for the current request, if any.

Types

type MatcherFunc

type MatcherFunc func(*http.Request, *RouteMatch) bool

MatcherFunc is the function signature used by custom matchers.

func (MatcherFunc) Match

func (m MatcherFunc) Match(r *http.Request, match *RouteMatch) bool

type Route

type Route struct {
	// contains filtered or unexported fields
}

Route stores information to match a request and build URLs.

func CurrentRoute

func CurrentRoute(r *http.Request) *Route

CurrentRoute returns the matched route for the current request, if any.

func (*Route) BuildOnly

func (r *Route) BuildOnly() *Route

BuildOnly sets the route to never match: it is only used to build URLs.

func (*Route) GetError

func (r *Route) GetError() error

GetError returns an error resulted from building the route, if any.

func (*Route) GetHandler

func (r *Route) GetHandler() http.Handler

GetHandler returns the handler for the route, if any.

func (*Route) GetName

func (r *Route) GetName() string

GetName returns the name for the route, if any.

func (*Route) Handler

func (r *Route) Handler(handler http.Handler) *Route

Handler sets a handler for the route.

func (*Route) HandlerFunc

func (r *Route) HandlerFunc(f func(http.ResponseWriter, *http.Request)) *Route

HandlerFunc sets a handler function for the route.

func (*Route) Headers

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()
r.Headers("Content-Type", "application/json",
          "X-Requested-With", "XMLHttpRequest")

The above route will only match if both request header values match.

It the value is an empty string, it will match any value if the key is set.

func (*Route) Host

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 me matched:

- {name} matches anything until the next dot.

- {name:pattern} matches the given regexp pattern.

For example:

r := mux.NewRouter()
r.Host("www.domain.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 (*Route) Match

func (r *Route) Match(req *http.Request, match *RouteMatch) bool

Match matches the route against the request.

func (*Route) MatcherFunc

func (r *Route) MatcherFunc(f MatcherFunc) *Route

MatcherFunc adds a custom function to be used as request matcher.

func (*Route) Methods

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 (*Route) Name

func (r *Route) Name(name string) *Route

Name sets the name for the route, used to build URLs. If the name was registered already it will be overwritten.

func (*Route) Path

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 me matched:

- {name} matches anything until the next slash.

- {name:pattern} matches the given regexp pattern.

For example:

r := mux.NewRouter()
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 (*Route) PathPrefix

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 (*Route) Queries

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()
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.

It the value is an empty string, it will match any value if the key is set.

Variables can define an optional regexp pattern to me matched:

- {name} matches anything until the next slash.

- {name:pattern} matches the given regexp pattern.

func (*Route) Schemes

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".

func (*Route) Subrouter

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()
s := r.Host("www.domain.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 (*Route) URL

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.Host("{subdomain}.domain.com").
  HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
  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")

All variables defined in the route are required, and their values must conform to the corresponding patterns.

func (*Route) URLHost

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 (*Route) URLPath

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.

type RouteMatch

type RouteMatch struct {
	Route   *Route
	Handler http.Handler
	Vars    map[string]string
}

RouteMatch stores information about a matched route.

type Router

type Router struct {
	// Configurable Handler to be used when no route matches.
	NotFoundHandler http.Handler

	// If true, do not clear the request context after handling the request
	KeepContext bool
	// contains filtered or unexported fields
}

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.

func NewRouter

func NewRouter() *Router

NewRouter returns a new router instance.

func (*Router) Get

func (r *Router) Get(name string) *Route

Get returns a route registered with the given name.

func (*Router) GetRoute

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 (*Router) Handle

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 (*Router) HandleFunc

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 (*Router) Headers

func (r *Router) Headers(pairs ...string) *Route

Headers registers a new route with a matcher for request header values. See Route.Headers().

func (*Router) Host

func (r *Router) Host(tpl string) *Route

Host registers a new route with a matcher for the URL host. See Route.Host().

func (*Router) Match

func (r *Router) Match(req *http.Request, match *RouteMatch) bool

Match matches registered routes against the request.

func (*Router) MatcherFunc

func (r *Router) MatcherFunc(f MatcherFunc) *Route

MatcherFunc registers a new route with a custom matcher function. See Route.MatcherFunc().

func (*Router) Methods

func (r *Router) Methods(methods ...string) *Route

Methods registers a new route with a matcher for HTTP methods. See Route.Methods().

func (*Router) NewRoute

func (r *Router) NewRoute() *Route

NewRoute registers an empty route.

func (*Router) Path

func (r *Router) Path(tpl string) *Route

Path registers a new route with a matcher for the URL path. See Route.Path().

func (*Router) PathPrefix

func (r *Router) PathPrefix(tpl string) *Route

PathPrefix registers a new route with a matcher for the URL path prefix. See Route.PathPrefix().

func (*Router) Queries

func (r *Router) Queries(pairs ...string) *Route

Queries registers a new route with a matcher for URL query values. See Route.Queries().

func (*Router) Schemes

func (r *Router) Schemes(schemes ...string) *Route

Schemes registers a new route with a matcher for URL schemes. See Route.Schemes().

func (*Router) ServeHTTP

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 (*Router) StrictSlash

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 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.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL