mux

package
v0.0.0-...-456eabd Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2011 License: BSD-3-Clause Imports: 9 Imported by: 0

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:

* URL hosts and paths can be defined using named variables with an optional regexp.

* Registered URLs can be built, or "reversed", which helps maintaining references to resources.

* Requests can also be matched based on HTTP methods, URL schemes, header and query values or using custom matchers.

* Routes can be nested, so that they are only tested if the parent route matches. This allows defining 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 is compatible with http.ServeMux: it can register handlers that implement the http.Handler interface or the signature accepted by http.HandleFunc().

The most basic example is to register a couple of URL paths and handlers:

r := new(mux.Router)
r.HandleFunc("/", HomeHandler)
r.HandleFunc("/products", ProductsHandler)
r.HandleFunc("/articles", ArticlesHandler)

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 notation {name} or {name:pattern}. If a regular expression pattern is not defined, the variable will be anything until the next slash. For example:

r := new(mux.Router)
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 := new(mux.Router)
// Only matches if domain is "www.domain.com".
r.HandleFunc("/products", ProductsHandler).Host("www.domain.com")
// Matches a dynamic subdomain.
r.HandleFunc("/products", ProductsHandler).
	Host("{subdomain:[a-z]+}.domain.com")

There are several other matchers that can be added. To match HTTP methods:

r.HandleFunc("/products", ProductsHandler).Methods("GET", "POST")

...or to match a given URL scheme:

r.HandleFunc("/products", ProductsHandler).Schemes("https")

...or to match specific header values:

r.HandleFunc("/products", ProductsHandler).
  Headers("X-Requested-With", "XMLHttpRequest")

...or to match specific URL query values:

r.HandleFunc("/products", ProductsHandler).Queries("key", "value")

...or to use a custom matcher function:

r.HandleFunc("/products", ProductsHandler).Matcher(MatcherFunc)

...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". We create a route for that host, then add a "subrouter" to that route:

r := new(mux.Router)
subrouter := r.NewRoute().Host("www.domain.com").NewRouter()

Then register routes for the host subrouter:

subrouter.HandleFunc("/products/", ProductsHandler)
subrouter.HandleFunc("/products/{key}", ProductHandler)
subrouter.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.

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 := new(mux.Router)
r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
  Name("article")

Named routes are available in the NamedRoutes field from a router. 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 := r.NamedRoutes["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 := new(mux.Router)
r.NewRoute().
  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 := r.NamedRoutes["article"].URL("subdomain", "news",
									  "category", "technology",
									  "id", "42")

All variable names defined in the route are required, and their values must conform to the corresponding patterns, if any.

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 := r.NamedRoutes["article"].URLHost("subdomain", "news").String()

// "/articles/technology/42"
path := r.NamedRoutes["article"].URLPath("category", "technology",
										   "id", "42").String()

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type MatcherFunc

type MatcherFunc func(*http.Request) bool

MatcherFunc is the type used by custom matchers.

type Route

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

Route stores information to match a request.

func CurrentRoute

func CurrentRoute(request *http.Request) *Route

CurrentRoute returns the currently matched route, if any.

func (*Route) Clone

func (r *Route) Clone() *Route

Clone clones a route.

func (*Route) GetName

func (r *Route) GetName() string

GetName returns the name associated with a route, if any.

func (*Route) Handle

func (r *Route) Handle(path string, handler http.Handler) *Route

Handle sets a path and handler for the route.

func (*Route) HandleFunc

func (r *Route) HandleFunc(path string, handler func(http.ResponseWriter,
	*http.Request)) *Route

HandleFunc sets a path and handler function for the route.

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(handler 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 to match the request against header values.

It accepts a sequence of key/value pairs to be matched. For example:

r := new(mux.Router)
r.NewRoute().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(template string) *Route

Host adds a matcher to match the request against 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 := new(mux.Router)
r.NewRoute().Host("www.domain.com")
r.NewRoute().Host("{subdomain}.domain.com")
r.NewRoute().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) (*RouteMatch, bool)

Match matches this route against the request.

It sets variables from the matched route in the context, if any.

func (*Route) Matcher

func (r *Route) Matcher(matcherFunc MatcherFunc) *Route

Matcher adds a matcher to match the request using a custom function.

func (*Route) Methods

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

Methods adds a matcher to match the request against 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 route name, used to build URLs.

A name must be unique for a router. If the name was registered already it will be overwritten.

func (*Route) NewRouter

func (r *Route) NewRouter() *Router

NewRouter creates a new router and adds it as a matcher for this route.

This is used for subrouting: it will test the inner routes if other matchers matched. For example:

r := new(mux.Router)
subrouter := r.NewRoute().Host("www.domain.com").NewRouter()
subrouter.HandleFunc("/products/", ProductsHandler)
subrouter.HandleFunc("/products/{key}", ProductHandler)
subrouter.HandleFunc("/articles/{category}/{id:[0-9]+}"),
                     ArticleHandler)

In this example, the routes registered in the subrouter will only be tested if the host matches.

func (*Route) Path

func (r *Route) Path(template string) *Route

Path adds a matcher to match the request against the URL path.

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

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

For example:

r := new(mux.Router)
r.NewRoute().Path("/products/").Handler(ProductsHandler)
r.NewRoute().Path("/products/{key}").Handler(ProductsHandler)
r.NewRoute().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(template string) *Route

PathPrefix adds a matcher to match the request against a URL path prefix.

func (*Route) Queries

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

Queries adds a matcher to match the request against URL query values.

It accepts a sequence of key/value pairs to be matched. For example:

r := new(mux.Router)
r.NewRoute().Queries("foo", "bar",
                     "baz", "ding")

The above route will only match if the URL contains the defined queries values, e.g.: ?foo=bar&baz=ding.

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

func (*Route) RedirectSlash

func (r *Route) RedirectSlash(value bool) *Route

RedirectSlash defines the redirectSlash behavior for this route.

When true, if the route path is /path/, accessing /path will redirect to /path/, and vice versa.

func (*Route) Schemes

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

Schemes adds a matcher to match the request against URL schemes.

It accepts a sequence of one or more schemes to be matched, e.g.: "http", "https".

func (*Route) URL

func (r *Route) URL(pairs ...string) (rv *url.URL)

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 := new(mux.Router)
r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
  Name("article")

...a URL for it can be built using:

url := r.NamedRoutes["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 := new(mux.Router)
r.NewRoute().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 := r.NamedRoutes["article"].URL("subdomain", "news",
                                    "category", "technology",
                                    "id", "42")

All variable names defined in the route are required, and their values must conform to the corresponding patterns, if any.

In case of bad arguments it will return nil.

func (*Route) URLDebug

func (r *Route) URLDebug(pairs ...string) (rv *url.URL, err error)

URLDebug is a debug version of URL: it also returns an error in case of failure.

func (*Route) URLHost

func (r *Route) URLHost(pairs ...string) (rv *url.URL)

URLHost builds the host part of the URL for a route.

The route must have a host defined.

In case of bad arguments or missing host it will return nil.

func (*Route) URLHostDebug

func (r *Route) URLHostDebug(pairs ...string) (rv *url.URL, err error)

URLHostDebug is a debug version of URLHost: it also returns an error in case of failure.

func (*Route) URLPath

func (r *Route) URLPath(pairs ...string) (rv *url.URL)

URLPath builds the path part of the URL for a route.

The route must have a path defined.

In case of bad arguments or missing path it will return nil.

func (*Route) URLPathDebug

func (r *Route) URLPathDebug(pairs ...string) (rv *url.URL, err error)

URLPathDebug is a debug version of URLPath: it also returns an error in case of failure.

type RouteMatch

type RouteMatch struct {
	Route   *Route
	Handler http.Handler
}

routeMatch is the returned result when a route matches.

type RouteVars

type RouteVars map[string]string

Vars stores the variables extracted from a URL.

func Vars

func Vars(request *http.Request) RouteVars

Vars returns the route variables for the matched route in a given request.

type Router

type Router struct {
	// Routes to be matched, in order.
	Routes []*Route
	// Routes by name, for URL building.
	NamedRoutes map[string]*Route

	// Configurable Handler to be used when no route matches.
	NotFoundHandler http.Handler
	// 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. For example, to send all incoming requests to the default router:

var router = new(mux.Router)

func main() {
    http.Handle("/", router)
}

Or, for Google App Engine, register it in a init() function:

var router = new(mux.Router)

func init() {
    http.Handle("/", router)
}

The DefaultRouter is a Router instance ready to register URLs and handlers. If needed, new instances can be created and registered.

func (*Router) AddRoute

func (r *Router) AddRoute(route *Route) *Router

AddRoute registers a route in the router.

func (*Router) Handle

func (r *Router) Handle(path string, handler http.Handler) *Route

Handle registers a new route and sets a path and handler.

See also: Route.Handle().

func (*Router) HandleFunc

func (r *Router) HandleFunc(path string, handler func(http.ResponseWriter,
	*http.Request)) *Route

HandleFunc registers a new route and sets a path and handler function.

See also: Route.HandleFunc().

func (*Router) Match

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

Match matches registered routes against the request.

func (*Router) NewRoute

func (r *Router) NewRoute() *Route

NewRoute creates an empty route and registers it in the router.

func (*Router) RedirectSlash

func (r *Router) RedirectSlash(value bool) *Router

RedirectSlash defines the default RedirectSlash behavior for new routes.

See Route.RedirectSlash.

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(writer http.ResponseWriter, request *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).

Jump to

Keyboard shortcuts

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