containous/mux

Name: mux

Owner: Containous

Description: A powerful URL router and dispatcher for golang.

Created: 2016-06-03 11:35:57.0

Updated: 2017-10-03 11:39:52.0

Pushed: 2018-05-17 17:36:27.0

Homepage: http://www.gorillatoolkit.org/pkg/mux

Size: 276

Language: Go

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

gorilla/mux

GoDoc Build Status Sourcegraph

Gorilla Logo

http://www.gorillatoolkit.org/pkg/mux

Package gorilla/mux implements a request router and dispatcher for matching incoming requests to their respective handler.

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:



Install

With a correctly configured Go toolchain:

et -u github.com/gorilla/mux
Examples

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

 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:

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

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

 ArticlesCategoryHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Category: %v\n", vars["category"])

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

Matching Routes

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

 mux.NewRouter()
nly matches if domain is "www.example.com".
st("www.example.com")
atches a dynamic subdomain.
st("{subdomain:[a-z]+}.domain.com")

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

thPrefix("/products/")

…or HTTP methods:

thods("GET", "POST")

…or URL schemes:

hemes("https")

…or header values:

aders("X-Requested-With", "XMLHttpRequest")

…or query values:

eries("key", "value")

…or to use a custom matcher function:

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

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

ndleFunc("/products", ProductsHandler).
st("www.example.com").
thods("GET").
hemes("http")

Routes are tested in the order they were added to the router. If two routes match, the first one wins:

 mux.NewRouter()
ndleFunc("/specific", specificHandler)
thPrefix("/").Handler(catchAllHandler)

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.example.com. Create a route for that host and get a “subrouter” from it:

 mux.NewRouter()
 r.Host("www.example.com").Subrouter()

Then register routes in the subrouter:

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

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.

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:

 mux.NewRouter()
 r.PathPrefix("/products").Subrouter()
/products/"
ndleFunc("/", ProductsHandler)
/products/{key}/"
ndleFunc("/{key}/", ProductHandler)
/products/{key}/details"
ndleFunc("/{key}/details", ProductDetailsHandler)
Listing Routes

Routes on a mux can be listed using the Router.Walk method?useful for generating documentation:

age main

rt (
"fmt"
"net/http"
"strings"

"github.com/gorilla/mux"


 handler(w http.ResponseWriter, r *http.Request) {
return


 main() {
r := mux.NewRouter()
r.HandleFunc("/", handler)
r.HandleFunc("/products", handler).Methods("POST")
r.HandleFunc("/articles", handler).Methods("GET")
r.HandleFunc("/articles/{id}", handler).Methods("GET", "PUT")
r.HandleFunc("/authors", handler).Queries("surname", "{surname}")
r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
    t, err := route.GetPathTemplate()
    if err != nil {
        return err
    }
    qt, err := route.GetQueriesTemplates()
    if err != nil {
        return err
    }
    // p will contain regular expression is compatible with regular expression in Perl, Python, and other languages.
    // for instance the regular expression for path '/articles/{id}' will be '^/articles/(?P<v0>[^/]+)$'
    p, err := route.GetPathRegexp()
    if err != nil {
        return err
    }
    // qr will contain a list of regular expressions with the same semantics as GetPathRegexp,
    // just applied to the Queries pairs instead, e.g., 'Queries("surname", "{surname}") will return
    // {"^surname=(?P<v0>.*)$}. Where each combined query pair will have an entry in the list.
    qr, err := route.GetQueriesRegexp()
    if err != nil {
        return err
    }
    m, err := route.GetMethods()
    if err != nil {
        return err
    }
    fmt.Println(strings.Join(m, ","), strings.Join(qt, ","), strings.Join(qr, ","), t, p)
    return nil
})
http.Handle("/", r)

Static Files

Note that the path provided to PathPrefix() represents a “wildcard”: calling PathPrefix("/static/").Handler(...) means that the handler will be passed any request that matches “/static/*“. This makes it easy to serve static files with mux:

 main() {
var dir string

flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir")
flag.Parse()
r := mux.NewRouter()

// This will serve files under http://localhost:8000/static/<filename>
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir))))

srv := &http.Server{
    Handler:      r,
    Addr:         "127.0.0.1:8000",
    // Good practice: enforce timeouts for servers you create!
    WriteTimeout: 15 * time.Second,
    ReadTimeout:  15 * time.Second,
}

log.Fatal(srv.ListenAndServe())

Registered URLs

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:

 mux.NewRouter()
ndleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
me("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:

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

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

ticles/technology/42"

This also works for host and query value variables:

 mux.NewRouter()
st("{subdomain}.domain.com").
th("/articles/{category}/{id:[0-9]+}").
eries("filter", "{filter}").
ndlerFunc(ArticleHandler).
me("article")

rl.String() will be "http://news.domain.com/articles/technology/42?filter=gorilla"
 err := r.Get("article").URL("subdomain", "news",
                             "category", "technology",
                             "id", "42",
                             "filter", "gorilla")

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.

Regex support also exists for matching Headers within a route. For example, we could do:

adersRegexp("Content-Type", "application/(text|json)")

…and the route will match both requests with a Content-Type of application/json as well as application/text

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/"
, err := r.Get("article").URLHost("subdomain", "news")

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

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

 mux.NewRouter()
 r.Host("{subdomain}.domain.com").Subrouter()
th("/articles/{category}/{id:[0-9]+}").
ndlerFunc(ArticleHandler).
me("article")

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

The Walk function on mux.Router can be used to visit all of the routes that are registered on a router. For example, the following prints all of the registered routes:

 mux.NewRouter()
ndleFunc("/", handler)
ndleFunc("/products", handler).Methods("POST")
ndleFunc("/articles", handler).Methods("GET")
ndleFunc("/articles/{id}", handler).Methods("GET", "PUT")
ndleFunc("/authors", handler).Queries("surname", "{surname}")
lk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
t, err := route.GetPathTemplate()
if err != nil {
    return err
}
qt, err := route.GetQueriesTemplates()
if err != nil {
    return err
}
// p will contain a regular expression that is compatible with regular expressions in Perl, Python, and other languages.
// For example, the regular expression for path '/articles/{id}' will be '^/articles/(?P<v0>[^/]+)$'.
p, err := route.GetPathRegexp()
if err != nil {
    return err
}
// qr will contain a list of regular expressions with the same semantics as GetPathRegexp,
// just applied to the Queries pairs instead, e.g., 'Queries("surname", "{surname}") will return
// {"^surname=(?P<v0>.*)$}. Where each combined query pair will have an entry in the list.
qr, err := route.GetQueriesRegexp()
if err != nil {
    return err
}
m, err := route.GetMethods()
if err != nil {
    return err
}
fmt.Println(strings.Join(m, ","), strings.Join(qt, ","), strings.Join(qr, ","), t, p)
return nil

Full Example

Here's a complete, runnable example of a small mux based server:

age main

rt (
"net/http"
"log"
"github.com/gorilla/mux"


 YourHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Gorilla!\n"))


 main() {
r := mux.NewRouter()
// Routes consist of a path and a handler function.
r.HandleFunc("/", YourHandler)

// Bind to a port and pass our router in
log.Fatal(http.ListenAndServe(":8000", r))

License

BSD licensed. See the LICENSE file for details.


This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.