mux

package
v0.6.9-alpha.12 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2023 License: Apache-2.0, BSD-3-Clause Imports: 9 Imported by: 0

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:

  • It implements the http.Handler interface so it is compatible with the standard http.ServeMux.
  • Requests can be matched based on URL host, path, path prefix, schemes, header and query values, HTTP methods or using custom matchers.
  • URL hosts, paths and query values 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.


Install

With a correctly configured Go toolchain:

go get -u github.com/gorilla/mux

Examples

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

func 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:

r := mux.NewRouter()
// Only matches if domain is "www.example.com".
r.Host("www.example.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.example.com").
  Methods("GET").
  Schemes("http")

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

r := mux.NewRouter()
r.HandleFunc("/specific", specificHandler)
r.PathPrefix("/").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:

r := mux.NewRouter()
s := r.Host("www.example.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.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:

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)
Listing Routes

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

package main

import (
    "fmt"
    "net/http"
    "strings"

    "github.com/gorilla/mux"
)

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

func 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:

func 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:

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 and query value variables:

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

// url.String() will be "http://news.domain.com/articles/technology/42?filter=gorilla"
url, 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:

r.HeadersRegexp("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/"
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")
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:

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 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
})
Graceful Shutdown

Go 1.8 introduced the ability to gracefully shutdown a *http.Server. Here's how to do that alongside mux:

package main

import (
    "context"
    "flag"
    "log"
    "net/http"
    "os"
    "os/signal"

    "github.com/gorilla/mux"
)

func main() {
    var wait time.Duration
    flag.DurationVar(&wait, "graceful-timeout", time.Second * 15, "the duration for which the server gracefully wait for existing connections to finish - e.g. 15s or 1m")
    flag.Parse()

    r := mux.NewRouter()
    // Add your routes as needed
    
    srv := &http.Server{
        Addr:         "0.0.0.0:8080",
        // Good practice to set timeouts to avoid Slowloris attacks.
        WriteTimeout: time.Second * 15,
        ReadTimeout:  time.Second * 15,
        IdleTimeout:  time.Second * 60,
        Handler: r, // Pass our instance of gorilla/mux in.
    }

    // Run our server in a goroutine so that it doesn't block.
    go func() {
        if err := srv.ListenAndServe(); err != nil {
            log.Println(err)
        }
    }()
    
    c := make(chan os.Signal, 1)
    // We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C)
    // SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught.
    signal.Notify(c, os.Interrupt)

    // Block until we receive our signal.
    <-c

    // Create a deadline to wait for.
    ctx, cancel := context.WithTimeout(ctx, wait)
    // Doesn't block if no connections, but will otherwise wait
    // until the timeout deadline.
    srv.Shutdown(ctx)
    // Optionally, you could run srv.Shutdown in a goroutine and block on
    // <-ctx.Done() if your application should wait for other services
    // to finalize based on context cancellation.
    log.Println("shutting down")
    os.Exit(0)
}

Full Example

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

package main

import (
    "net/http"
    "log"
    "github.com/gorilla/mux"
)

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

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

Documentation

Overview

Package 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, paths and query values 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)

Groups can be used inside patterns, as long as they are non-capturing (?:re). For example:

r.HandleFunc("/articles/{category}/{sort:(?:asc|desc|new)}", ArticlesCategoryHandler)

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

Note that if any capturing groups are present, mux will panic() during parsing. To prevent this, convert any capturing groups to non-capturing, e.g. change "/{sort:(asc|desc)}" to "/{sort:(?:asc|desc)}". This is a change from prior versions which behaved unpredictably when capturing groups were present.

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.example.com".
r.Host("www.example.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.example.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.example.com". Create a route for that host and get a "subrouter" from it:

r := mux.NewRouter()
s := r.Host("www.example.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.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:

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)

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:

func 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())
}

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 and query value variables:

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

// url.String() will be "http://news.domain.com/articles/technology/42?filter=gorilla"
url, 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:

r.HeadersRegexp("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/"
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

View Source
var (
	ErrMethodMismatch = errors.New("method is not allowed")
	ErrNotFound       = errors.New("no matching route was found")
)
View Source
var SkipRouter = errors.New("skip this router")

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.

Functions

func Vars

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

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

Types

type BuildVarsFunc

type BuildVarsFunc func(map[string]string) map[string]string

BuildVarsFunc is the function signature used by custom build variable functions (which can modify route variables before a route's URL is built).

type DefaultHandler

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

func NewDefaultHandler

func NewDefaultHandler(handle HandlerFunc) *DefaultHandler

func (*DefaultHandler) Serve

func (H *DefaultHandler) Serve(req *Request) (tview.Primitive, *Request, error)

type Handler

type Handler interface {
	Serve(*Request) (tview.Primitive, *Request, error)
}

type HandlerFunc

type HandlerFunc func(*Request) (tview.Primitive, *Request, error)

type MatcherFunc

type MatcherFunc func(*Request, *RouteMatch) bool

MatcherFunc is the function signature used by custom matchers.

func (MatcherFunc) Match

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

Match returns the match for a given request.

type MiddlewareFunc

type MiddlewareFunc func(Handler) Handler

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.

func (MiddlewareFunc) Middleware

func (mw MiddlewareFunc) Middleware(handler Handler) Handler

MiddlewareFunc also implements the middleware interface.

type Request

type Request struct {
	Path    string
	Queries map[string][]string

	Context map[string]interface{}
}

func SetURLVars

func SetURLVars(r *Request, val map[string]string) *Request

SetURLVars sets the URL variables for the given request, to be accessed via mux.Vars for testing route behaviour.

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.

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 *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, unless the KeepContext option is set on the Router.

func (*Route) BuildOnly

func (r *Route) BuildOnly() *Route

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

func (*Route) BuildVarsFunc

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 (*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() 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) GetPathRegexp

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

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

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 empty list will be returned if the route does not have queries.

func (*Route) GetQueriesTemplates

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 empty list will be returned if the route does not define queries.

func (*Route) Handler

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

Handler sets a handler for the route.

func (*Route) HandlerFunc

func (R *Route) HandlerFunc(HandlerFunc)

func (*Route) Match

func (r *Route) Match(req *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) 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 be 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 be matched:

- {name} matches anything until the next slash.

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

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

func (r *Route) Substitute(pairs ...string) (string, error)

Substitute builds the full path from the template 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 Substitution for it can be built using:

url, err := r.Get("article").Substitute("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]+}?edit={edit}", ArticleHandler).
  Name("article")

// url.String() will be "/articles/technology/42?edit=true"
url, err := r.Get("article")
             .Substitute("category", "technology",
                         "id", "42",
                         "edit", "true")

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

type RouteMatch

type RouteMatch struct {
	Route   *Route
	Handler 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
}

RouteMatch stores information about a matched route.

type Router

type Router struct {
	// Configurable Handler to be used when no route matches.
	NotFoundHandler 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:

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) BuildVarsFunc

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

func (r *Router) Dispatch(fullpath string, context map[string]interface{}) (tview.Primitive, *Request, error)

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) 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 Handler) *Route

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

func (*Router) Match

func (r *Router) Match(req *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 (*Router) MatcherFunc

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

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

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) Serve

func (r *Router) Serve(req *Request) (tview.Primitive, *Request, error)

func (*Router) Use

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

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.

type WalkFunc

type WalkFunc func(route *Route, router *Router, ancestors []*Route) error

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.

Jump to

Keyboard shortcuts

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