mux
packagemoduleThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
README¶
gorilla/mux
Packagegorilla/mux implements a request router and dispatcher for matching incoming requests totheir respective handler.
The name mux stands for "HTTP request multiplexer". Like the standardhttp.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.Handlerinterface so it is compatible with the standardhttp.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
- Examples
- Matching Routes
- Static Files
- Serving Single Page Applications (e.g. React, Vue, Ember.js, etc.)
- Registered URLs
- Walking Routes
- Graceful Shutdown
- Middleware
- Handling CORS Requests
- Testing Handlers
- Full Example
Install
With acorrectly configured Go toolchain:
go get -u github.com/gorilla/muxExamples
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 howhttp.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 callingmux.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]+}.example.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 iswww.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 iswww.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)Static Files
Note that the path provided toPathPrefix() represents a "wildcard": callingPathPrefix("/static/").Handler(...) means that the handler will be passed anyrequest 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())}Serving Single Page Applications
Most of the time it makes sense to serve your SPA on a separate web server from your API,but sometimes it's desirable to serve them both from one place. It's possible to write a simplehandler for serving your SPA (for use with React Router'sBrowserRouter for example), and leveragemux's powerful routing for your API endpoints.
package mainimport ("encoding/json""log""net/http""os""path/filepath""time""github.com/gorilla/mux")// spaHandler implements the http.Handler interface, so we can use it// to respond to HTTP requests. The path to the static directory and// path to the index file within that static directory are used to// serve the SPA in the given static directory.type spaHandler struct {staticPath stringindexPath string}// ServeHTTP inspects the URL path to locate a file within the static dir// on the SPA handler. If a file is found, it will be served. If not, the// file located at the index path on the SPA handler will be served. This// is suitable behavior for serving an SPA (single page application).func (h spaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {// Join internally call path.Clean to prevent directory traversalpath := filepath.Join(h.staticPath, r.URL.Path)// check whether a file exists or is a directory at the given pathfi, err := os.Stat(path)if os.IsNotExist(err) || fi.IsDir() {// file does not exist or path is a directory, serve index.htmlhttp.ServeFile(w, r, filepath.Join(h.staticPath, h.indexPath))return}if err != nil {// if we got an error (that wasn't that the file doesn't exist) stating the// file, return a 500 internal server error and stophttp.Error(w, err.Error(), http.StatusInternalServerError) return}// otherwise, use http.FileServer to serve the static filehttp.FileServer(http.Dir(h.staticPath)).ServeHTTP(w, r)}func main() {router := mux.NewRouter()router.HandleFunc("/api/health", func(w http.ResponseWriter, r *http.Request) {// an example API handlerjson.NewEncoder(w).Encode(map[string]bool{"ok": true})})spa := spaHandler{staticPath: "build", indexPath: "index.html"}router.PathPrefix("/").Handler(spa)srv := &http.Server{Handler: router,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 callingName() 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 theURL() 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 aurl.URL with the following path:
"/articles/technology/42"This also works for host and query value variables:
r := mux.NewRouter()r.Host("{subdomain}.example.com"). Path("/articles/{category}/{id:[0-9]+}"). Queries("filter", "{filter}"). HandlerFunc(ArticleHandler). Name("article")// url.String() will be "http://news.example.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 ofapplication/json as well asapplication/text
There's also a way to build only the URL host or path for a route: use the methodsURLHost() orURLPath() instead. For the previous route, we would do:
// "http://news.example.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}.example.com").Subrouter()s.Path("/articles/{category}/{id:[0-9]+}"). HandlerFunc(ArticleHandler). Name("article")// "http://news.example.com/articles/technology/42"url, err := r.Get("article").URL("subdomain", "news", "category", "technology", "id", "42")To find all the required variables for a given route when callingURL(), the methodGetVarNames() is available:
r := mux.NewRouter()r.Host("{domain}"). Path("/{group}/{item_id}"). Queries("some_data1", "{some_data1}"). Queries("some_data2", "{some_data2}"). Name("article")// Will print [domain group item_id some_data1 some_data2] <nil>fmt.Println(r.Get("article").GetVarNames())Walking Routes
TheWalk function onmux.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:
package mainimport ("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}")err := r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {pathTemplate, err := route.GetPathTemplate()if err == nil {fmt.Println("ROUTE:", pathTemplate)}pathRegexp, err := route.GetPathRegexp()if err == nil {fmt.Println("Path regexp:", pathRegexp)}queriesTemplates, err := route.GetQueriesTemplates()if err == nil {fmt.Println("Queries templates:", strings.Join(queriesTemplates, ","))}queriesRegexps, err := route.GetQueriesRegexp()if err == nil {fmt.Println("Queries regexps:", strings.Join(queriesRegexps, ","))}methods, err := route.GetMethods()if err == nil {fmt.Println("Methods:", strings.Join(methods, ","))}fmt.Println()return nil})if err != nil {fmt.Println(err)}http.Handle("/", r)}Graceful Shutdown
Go 1.8 introduced the ability togracefully shutdown a*http.Server. Here's how to do that alongsidemux:
package mainimport ( "context" "flag" "log" "net/http" "os" "os/signal" "time" "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(context.Background(), wait) defer cancel() // 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)}Middleware
Mux supports the addition of middlewares to aRouter, which are executed in the order they are added if a match is found, including its subrouters.Middlewares are (typically) small pieces of code which take one request, do something with it, and pass it down to another middleware or the final handler. Some common use cases for middleware are request logging, header manipulation, orResponseWriter hijacking.
Mux middlewares are defined using the de facto standard type:
type MiddlewareFunc func(http.Handler) http.HandlerTypically, 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. This takes advantage of closures being able access variables from the context where they are created, while retaining the signature enforced by the receivers.
A very basic middleware which logs the URI of the request being handled could be written as:
func loggingMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Do stuff here log.Println(r.RequestURI) // Call the next handler, which can be another middleware in the chain, or the final handler. next.ServeHTTP(w, r) })}Middlewares can be added to a router usingRouter.Use():
r := mux.NewRouter()r.HandleFunc("/", handler)r.Use(loggingMiddleware)A more complex authentication middleware, which maps session token to users, could be written as:
// Define our structtype authenticationMiddleware struct {tokenUsers map[string]string}// Initialize it somewherefunc (amw *authenticationMiddleware) Populate() {amw.tokenUsers["00000000"] = "user0"amw.tokenUsers["aaaaaaaa"] = "userA"amw.tokenUsers["05f717e5"] = "randomUser"amw.tokenUsers["deadbeef"] = "user0"}// Middleware function, which will be called for each requestfunc (amw *authenticationMiddleware) Middleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { token := r.Header.Get("X-Session-Token") if user, found := amw.tokenUsers[token]; found { // We found the token in our map log.Printf("Authenticated user %s\n", user) // Pass down the request to the next middleware (or final handler) next.ServeHTTP(w, r) } else { // Write an error and stop the handler chain http.Error(w, "Forbidden", http.StatusForbidden) } })}r := mux.NewRouter()r.HandleFunc("/", handler)amw := authenticationMiddleware{tokenUsers: make(map[string]string)}amw.Populate()r.Use(amw.Middleware)Note: The handler chain will be stopped if your middleware doesn't callnext.ServeHTTP() with the corresponding parameters. This can be used to abort a request if the middleware writer wants to. Middlewaresshould write toResponseWriter if theyare going to terminate the request, and theyshould not write toResponseWriter if theyare not going to terminate it.
Handling CORS Requests
CORSMethodMiddleware intends to make it easier to strictly set theAccess-Control-Allow-Methods response header.
- You will still need to use your own CORS handler to set the other CORS headers such as
Access-Control-Allow-Origin - The middleware will set the
Access-Control-Allow-Methodsheader to all the method matchers (e.g.r.Methods(http.MethodGet, http.MethodPut, http.MethodOptions)->Access-Control-Allow-Methods: GET,PUT,OPTIONS) on a route - If you do not specify any methods, then:
Important: there must be an
OPTIONSmethod matcher for the middleware to set the headers.
Here is an example of usingCORSMethodMiddleware along with a customOPTIONS handler to set all the required CORS headers:
package mainimport ("net/http""github.com/gorilla/mux")func main() { r := mux.NewRouter() // IMPORTANT: you must specify an OPTIONS method matcher for the middleware to set CORS headers r.HandleFunc("/foo", fooHandler).Methods(http.MethodGet, http.MethodPut, http.MethodPatch, http.MethodOptions) r.Use(mux.CORSMethodMiddleware(r)) http.ListenAndServe(":8080", r)}func fooHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") if r.Method == http.MethodOptions { return } w.Write([]byte("foo"))}And an request to/foo using something like:
curl localhost:8080/foo -vWould look like:
* Trying ::1...* TCP_NODELAY set* Connected to localhost (::1) port 8080 (#0)> GET /foo HTTP/1.1> Host: localhost:8080> User-Agent: curl/7.59.0> Accept: */*> < HTTP/1.1 200 OK< Access-Control-Allow-Methods: GET,PUT,PATCH,OPTIONS< Access-Control-Allow-Origin: *< Date: Fri, 28 Jun 2019 20:13:30 GMT< Content-Length: 3< Content-Type: text/plain; charset=utf-8< * Connection #0 to host localhost left intactfooTesting Handlers
Testing handlers in a Go web application is straightforward, andmux doesn't complicate this any further. Given two files:endpoints.go andendpoints_test.go, here's how we'd test an application usingmux.
First, our simple HTTP handler:
// endpoints.gopackage mainfunc HealthCheckHandler(w http.ResponseWriter, r *http.Request) { // A very simple health check. w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) // In the future we could report back on the status of our DB, or our cache // (e.g. Redis) by performing a simple PING, and include them in the response. io.WriteString(w, `{"alive": true}`)}func main() { r := mux.NewRouter() r.HandleFunc("/health", HealthCheckHandler) log.Fatal(http.ListenAndServe("localhost:8080", r))}Our test code:
// endpoints_test.gopackage mainimport ( "net/http" "net/http/httptest" "testing")func TestHealthCheckHandler(t *testing.T) { // Create a request to pass to our handler. We don't have any query parameters for now, so we'll // pass 'nil' as the third parameter. req, err := http.NewRequest("GET", "/health", nil) if err != nil { t.Fatal(err) } // We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response. rr := httptest.NewRecorder() handler := http.HandlerFunc(HealthCheckHandler) // Our handlers satisfy http.Handler, so we can call their ServeHTTP method // directly and pass in our Request and ResponseRecorder. handler.ServeHTTP(rr, req) // Check the status code is what we expect. if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } // Check the response body is what we expect. expected := `{"alive": true}` if rr.Body.String() != expected { t.Errorf("handler returned unexpected body: got %v want %v", rr.Body.String(), expected) }}In the case that our routes havevariables, we can pass those in the request. We could writetable-driven tests to test multiplepossible route variables as needed.
// endpoints.gofunc main() { r := mux.NewRouter() // A route with a route variable: r.HandleFunc("/metrics/{type}", MetricsHandler) log.Fatal(http.ListenAndServe("localhost:8080", r))}Our test file, with a table-driven test ofrouteVariables:
// endpoints_test.gofunc TestMetricsHandler(t *testing.T) { tt := []struct{ routeVariable string shouldPass bool }{ {"goroutines", true}, {"heap", true}, {"counters", true}, {"queries", true}, {"adhadaeqm3k", false}, } for _, tc := range tt { path := fmt.Sprintf("/metrics/%s", tc.routeVariable) req, err := http.NewRequest("GET", path, nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder()// To add the vars to the context, // we need to create a router through which we can pass the request.router := mux.NewRouter() router.HandleFunc("/metrics/{type}", MetricsHandler) router.ServeHTTP(rr, req) // In this case, our MetricsHandler returns a non-200 response // for a route variable it doesn't know about. if rr.Code == http.StatusOK && !tc.shouldPass { t.Errorf("handler should have failed on routeVariable %s: got %v want %v", tc.routeVariable, rr.Code, http.StatusOK) } }}Full Example
Here's a complete, runnable example of a smallmux based server:
package mainimport ( "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 standardhttp.ServeMux, mux.Router matches incoming requests against a list ofregistered routes and calls a handler for the route that matches the URLor 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 optionalregular expression.
- Registered URLs can be built, or "reversed", which helps maintainingreferences to resources.
- Routes can be used as subrouters: nested routes are only tested if theparent route matches. This is useful to define groups of routes thatshare common conditions like a host, a path prefix or other repeatedattributes. As a bonus, this optimizes request matching.
- It implements the http.Handler interface so it is compatible with thestandard 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 isequivalent to how http.HandleFunc() works: if an incoming request URL matchesone 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 matchedvariable 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 retrievedcalling mux.Vars():
vars := mux.Vars(request)category := vars["category"]
Note that if any capturing groups are present, mux will panic() during parsing. To preventthis, 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 unpredictablywhen capturing groups were present.
And this is all you need to know about the basic usage. More advanced optionsare explained below.
Routes can also be restricted to a domain or subdomain. Just define a hostpattern 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 havea 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 thehost 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 notonly convenient, but also optimizes request matching. You can createsubrouters combining any attribute matchers accepted by a route.
Subrouters can be used to create domain or path "namespaces": you definesubrouters in a central place and then parts of the app can register itspaths 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": callingPathPrefix("/static/").Handler(...) means that the handler will be passed anyrequest that matches "/static/*". This makes it easy to serve static files with mux:
func main() {var dir stringflag.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 ofkey/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 mustconform to the corresponding patterns. These requirements guarantee that agenerated URL will always match a registered route -- the only exception isfor 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 builtas 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")Mux supports the addition of middlewares to a Router, which are executed in the order they are added if a match is found, including its subrouters. Middlewares are (typically) small pieces of code which take one request, do something with it, and pass it down to another middleware or the final handler. Some common use cases for middleware are request logging, header manipulation, or ResponseWriter hijacking.
type MiddlewareFunc func(http.Handler) 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 (closures can access variables from the context where they are created).
A very basic middleware which logs the URI of the request being handled could be written as:
func simpleMw(next http.Handler) http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {// Do stuff herelog.Println(r.RequestURI)// Call the next handler, which can be another middleware in the chain, or the final handler.next.ServeHTTP(w, r)})}Middlewares can be added to a router using `Router.Use()`:
r := mux.NewRouter()r.HandleFunc("/", handler)r.Use(simpleMw)A more complex authentication middleware, which maps session token to users, could be written as:
// Define our structtype authenticationMiddleware struct {tokenUsers map[string]string}// Initialize it somewherefunc (amw *authenticationMiddleware) Populate() {amw.tokenUsers["00000000"] = "user0"amw.tokenUsers["aaaaaaaa"] = "userA"amw.tokenUsers["05f717e5"] = "randomUser"amw.tokenUsers["deadbeef"] = "user0"}// Middleware function, which will be called for each requestfunc (amw *authenticationMiddleware) Middleware(next http.Handler) http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {token := r.Header.Get("X-Session-Token")if user, found := amw.tokenUsers[token]; found {// We found the token in our maplog.Printf("Authenticated user %s\n", user)next.ServeHTTP(w, r)} else {http.Error(w, "Forbidden", http.StatusForbidden)}})}r := mux.NewRouter()r.HandleFunc("/", handler)amw := authenticationMiddleware{tokenUsers: make(map[string]string)}amw.Populate()r.Use(amw.Middleware)Note: The handler chain will be stopped if your middleware doesn't call `next.ServeHTTP()` with the corresponding parameters. This can be used to abort a request if the middleware writer wants to.
Example (AuthenticationMiddleware)¶
package mainimport ("log""net/http""github.com/gorilla/mux")// Define our structtype authenticationMiddleware struct {tokenUsers map[string]string}// Initialize it somewherefunc (amw *authenticationMiddleware) Populate() {amw.tokenUsers["00000000"] = "user0"amw.tokenUsers["aaaaaaaa"] = "userA"amw.tokenUsers["05f717e5"] = "randomUser"amw.tokenUsers["deadbeef"] = "user0"}// Middleware function, which will be called for each requestfunc (amw *authenticationMiddleware) Middleware(next http.Handler) http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {token := r.Header.Get("X-Session-Token")if user, found := amw.tokenUsers[token]; found {// We found the token in our maplog.Printf("Authenticated user %s\n", user)next.ServeHTTP(w, r)} else {http.Error(w, "Forbidden", http.StatusForbidden)}})}func main() {r := mux.NewRouter()r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {// Do something here})amw := authenticationMiddleware{make(map[string]string)}amw.Populate()r.Use(amw.Middleware)}Index¶
- Variables
- func SetURLVars(r *http.Request, val map[string]string) *http.Request
- func Vars(r *http.Request) map[string]string
- type BuildVarsFunc
- type MatcherFunc
- type MiddlewareFunc
- type Route
- func (r *Route) BuildOnly() *Route
- func (r *Route) BuildVarsFunc(f BuildVarsFunc) *Route
- func (r *Route) GetError() error
- func (r *Route) GetHandler() http.Handler
- func (r *Route) GetHostTemplate() (string, error)
- func (r *Route) GetMethods() ([]string, error)
- func (r *Route) GetName() string
- func (r *Route) GetPathRegexp() (string, error)
- func (r *Route) GetPathTemplate() (string, error)
- func (r *Route) GetQueriesRegexp() ([]string, error)
- func (r *Route) GetQueriesTemplates() ([]string, error)
- func (r *Route) GetVarNames() ([]string, error)
- func (r *Route) Handler(handler http.Handler) *Route
- func (r *Route) HandlerFunc(f func(http.ResponseWriter, *http.Request)) *Route
- func (r *Route) Headers(pairs ...string) *Route
- func (r *Route) HeadersRegexp(pairs ...string) *Route
- func (r *Route) Host(tpl string) *Route
- func (r *Route) Match(req *http.Request, match *RouteMatch) bool
- func (r *Route) MatcherFunc(f MatcherFunc) *Route
- func (r *Route) Methods(methods ...string) *Route
- func (r *Route) Name(name string) *Route
- func (r *Route) Path(tpl string) *Route
- func (r *Route) PathPrefix(tpl string) *Route
- func (r *Route) Queries(pairs ...string) *Route
- func (r *Route) Schemes(schemes ...string) *Route
- func (r *Route) SkipClean() bool
- func (r *Route) Subrouter() *Router
- func (r *Route) URL(pairs ...string) (*url.URL, error)
- func (r *Route) URLHost(pairs ...string) (*url.URL, error)
- func (r *Route) URLPath(pairs ...string) (*url.URL, error)
- type RouteMatch
- type Router
- func (r *Router) BuildVarsFunc(f BuildVarsFunc) *Route
- func (r *Router) Get(name string) *Route
- func (r *Router) GetRoute(name string) *Route
- func (r *Router) Handle(path string, handler http.Handler) *Route
- func (r *Router) HandleFunc(path string, f func(http.ResponseWriter, *http.Request)) *Route
- func (r *Router) Headers(pairs ...string) *Route
- func (r *Router) Host(tpl string) *Route
- func (r *Router) Match(req *http.Request, match *RouteMatch) bool
- func (r *Router) MatcherFunc(f MatcherFunc) *Route
- func (r *Router) Methods(methods ...string) *Route
- func (r *Router) Name(name string) *Route
- func (r *Router) NewRoute() *Route
- func (r *Router) Path(tpl string) *Route
- func (r *Router) PathPrefix(tpl string) *Route
- func (r *Router) Queries(pairs ...string) *Route
- func (r *Router) Schemes(schemes ...string) *Route
- func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (r *Router) SkipClean(value bool) *Router
- func (r *Router) StrictSlash(value bool) *Router
- func (r *Router) Use(mwf ...MiddlewareFunc)
- func (r *Router) UseEncodedPath() *Router
- func (r *Router) Walk(walkFn WalkFunc) error
- type WalkFunc
Examples¶
Constants¶
This section is empty.
Variables¶
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"))
var SkipRouter =errors.New("skip this router")SkipRouter is used as a return value from WalkFuncs to indicate that therouter that walk is about to descend down to should be skipped.
Functions¶
funcSetURLVars¶added inv1.6.1
SetURLVars sets the URL variables for the given request, to be accessed viamux.Vars for testing route behaviour. Arguments are not modified, a shallowcopy is returned.
This API should only be used for testing purposes; it provides a way toinject variables into the request context. Alternatively, URL variablescan be set by making a route that captures the required variables,starting a server and sending the request to that server.
Example¶
req, _ := http.NewRequest("GET", "/foo", nil)req = SetURLVars(req, map[string]string{"foo": "bar"})fmt.Println(Vars(req)["foo"])Output:bar
Types¶
typeBuildVarsFunc¶
BuildVarsFunc is the function signature used by custom build variablefunctions (which can modify route variables before a route's URL is built).
typeMatcherFunc¶
type MatcherFunc func(*http.Request, *RouteMatch)bool
MatcherFunc is the function signature used by custom matchers.
func (MatcherFunc)Match¶
func (mMatcherFunc) Match(r *http.Request, match *RouteMatch)bool
Match returns the match for a given request.
typeMiddlewareFunc¶added inv1.6.1
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 passedto it, and then calls the handler passed as parameter to the MiddlewareFunc.
funcCORSMethodMiddleware¶added inv1.6.2
func CORSMethodMiddleware(r *Router)MiddlewareFunc
CORSMethodMiddleware automatically sets the Access-Control-Allow-Methods response headeron requests for routes that have an OPTIONS method matcher to all the method matchers onthe route. Routes that do not explicitly handle OPTIONS requests will not be processedby the middleware. See examples for usage.
Example¶
package mainimport ("fmt""net/http""net/http/httptest""github.com/gorilla/mux")func main() {r := mux.NewRouter()r.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {// Handle the request}).Methods(http.MethodGet, http.MethodPut, http.MethodPatch)r.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {w.Header().Set("Access-Control-Allow-Origin", "http://example.com")w.Header().Set("Access-Control-Max-Age", "86400")}).Methods(http.MethodOptions)r.Use(mux.CORSMethodMiddleware(r))rw := httptest.NewRecorder()req, _ := http.NewRequest("OPTIONS", "/foo", nil) // needs to be OPTIONSreq.Header.Set("Access-Control-Request-Method", "POST") // needs to be non-emptyreq.Header.Set("Access-Control-Request-Headers", "Authorization") // needs to be non-emptyreq.Header.Set("Origin", "http://example.com") // needs to be non-emptyr.ServeHTTP(rw, req)fmt.Println(rw.Header().Get("Access-Control-Allow-Methods"))fmt.Println(rw.Header().Get("Access-Control-Allow-Origin"))}Output:GET,PUT,PATCH,OPTIONShttp://example.com
func (MiddlewareFunc)Middleware¶added inv1.6.1
func (mwMiddlewareFunc) Middleware(handlerhttp.Handler)http.Handler
Middleware allows MiddlewareFunc to implement the middleware interface.
typeRoute¶
type Route struct {// contains filtered or unexported fields}Route stores information to match a request and build URLs.
funcCurrentRoute¶
CurrentRoute returns the matched route for the current request, if any.This only works when called inside the handler of the matched routebecause the matched route is stored in the request context which is clearedafter the handler returns.
func (*Route)BuildVarsFunc¶
func (r *Route) BuildVarsFunc(fBuildVarsFunc) *Route
BuildVarsFunc adds a custom function to be used to modify build variablesbefore a route's URL is built.
func (*Route)GetHandler¶
GetHandler returns the handler for the route, if any.
func (*Route)GetHostTemplate¶
GetHostTemplate returns the template used to build theroute match.This is useful for building simple REST API documentation and for instrumentationagainst third-party services.An error will be returned if the route does not define a host.
func (*Route)GetMethods¶added inv1.4.0
GetMethods returns the methods the route matches againstThis is useful for building simple REST API documentation and for instrumentationagainst third-party services.An error will be returned if route does not have methods.
func (*Route)GetPathRegexp¶added inv1.4.0
GetPathRegexp returns the expanded regular expression used to match route path.This is useful for building simple REST API documentation and for instrumentationagainst third-party services.An error will be returned if the route does not define a path.
func (*Route)GetPathTemplate¶
GetPathTemplate returns the template used to build theroute match.This is useful for building simple REST API documentation and for instrumentationagainst third-party services.An error will be returned if the route does not define a path.
func (*Route)GetQueriesRegexp¶added inv1.6.0
GetQueriesRegexp returns the expanded regular expressions used to match theroute queries.This is useful for building simple REST API documentation and for instrumentationagainst third-party services.An error will be returned if the route does not have queries.
func (*Route)GetQueriesTemplates¶added inv1.6.0
GetQueriesTemplates returns the templates used to build thequery matching.This is useful for building simple REST API documentation and for instrumentationagainst third-party services.An error will be returned if the route does not define queries.
func (*Route)GetVarNames¶added inv1.8.1
GetVarNames returns the names of all variables added by regexp matchersThese can be used to know which route variables should be passed into r.URL()
Example¶
This example demonstrates building a dynamic URL usingrequired vars and values retrieve from another source
package mainimport ("fmt""github.com/gorilla/mux")func main() {r := mux.NewRouter()route := r.Host("{domain}").Path("/{group}/{item_id}").Queries("some_data1", "{some_data1}").Queries("some_data2_and_3", "{some_data2}.{some_data3}")dataSource := func(key string) string {return "my_value_for_" + key}varNames, _ := route.GetVarNames()pairs := make([]string, 0, len(varNames)*2)for _, varName := range varNames {pairs = append(pairs, varName, dataSource(varName))}url, err := route.URL(pairs...)if err != nil {panic(err)}fmt.Println(url.String())}func (*Route)HandlerFunc¶
HandlerFunc sets a handler function for the route.
func (*Route)Headers¶
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 (*Route)HeadersRegexp¶
HeadersRegexp accepts a sequence of key/value pairs, where the value has regexsupport. 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¶
This example demonstrates setting a regular expression matcher forthe header value. A plain word will match any value that contains amatching substring as if the pattern was wrapped with `.*`.
package mainimport ("fmt""net/http""github.com/gorilla/mux")func main() {r := mux.NewRouter()route := r.NewRoute().HeadersRegexp("Accept", "html")req1, _ := http.NewRequest("GET", "example.com", nil)req1.Header.Add("Accept", "text/plain")req1.Header.Add("Accept", "text/html")req2, _ := http.NewRequest("GET", "example.com", nil)req2.Header.Set("Accept", "application/xhtml+xml")matchInfo := &mux.RouteMatch{}fmt.Printf("Match: %v %q\n", route.Match(req1, matchInfo), req1.Header["Accept"])fmt.Printf("Match: %v %q\n", route.Match(req2, matchInfo), req2.Header["Accept"])}Output:Match: true ["text/plain" "text/html"]Match: true ["application/xhtml+xml"]
Example (ExactMatch)¶
This example demonstrates setting a strict regular expression matcherfor the header value. Using the start and end of string anchors, thevalue must be an exact match.
package mainimport ("fmt""net/http""github.com/gorilla/mux")func main() {r := mux.NewRouter()route := r.NewRoute().HeadersRegexp("Origin", "^https://example.co$")yes, _ := http.NewRequest("GET", "example.co", nil)yes.Header.Set("Origin", "https://example.co")no, _ := http.NewRequest("GET", "example.co.uk", nil)no.Header.Set("Origin", "https://example.co.uk")matchInfo := &mux.RouteMatch{}fmt.Printf("Match: %v %q\n", route.Match(yes, matchInfo), yes.Header["Origin"])fmt.Printf("Match: %v %q\n", route.Match(no, matchInfo), no.Header["Origin"])}Output:Match: true ["https://example.co"]Match: false ["https://example.co.uk"]
func (*Route)Host¶
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 retrievedcalling 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(fMatcherFunc) *Route
MatcherFunc adds a custom function to be used as request matcher.
func (*Route)Methods¶
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¶
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 (*Route)Path¶
Path adds a matcher for the URL path.It accepts a template with zero or more URL variables enclosed by {}. Thetemplate 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 retrievedcalling mux.Vars(request).
func (*Route)PathPrefix¶
PathPrefix adds a matcher for the URL path prefix. This matches if the giventemplate is a prefix of the full URL path. See Route.Path() for details onthe tpl argument.
Note that it does not treat slashes specially ("/foobar/" will be matched bythe prefix "/foo") so you may want to use a trailing slash here.
Also note that the setting of Router.StrictSlash() has no effect on routeswith a PathPrefix matcher.
func (*Route)Queries¶
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 queriesvalues, 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 (*Route)Schemes¶
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 TLStermination state.The first argument to Schemes will be used when constructing a route URL.
func (*Route)SkipClean¶
SkipClean reports whether path cleaning is enabled for this route viaRouter.SkipClean.
func (*Route)Subrouter¶
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 hostdoesn't match.
func (*Route)URL¶
URL builds a URL for the route.
It accepts a sequence of key/value pairs for the route variables. Forexample, 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 mustconform to the corresponding patterns.
typeRouteMatch¶
type RouteMatch struct {Route *RouteHandlerhttp.HandlerVars 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 methodMatchErrerror}RouteMatch stores information about a matched route.
typeRouter¶
type Router struct {// Configurable Handler to be used when no route matches.// This can be used to render your own 404 Not Found errors.NotFoundHandlerhttp.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.MethodNotAllowedHandlerhttp.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.KeepContextbool// 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 serverequests:
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 (*Router)BuildVarsFunc¶
func (r *Router) BuildVarsFunc(fBuildVarsFunc) *Route
BuildVarsFunc registers a new route with a custom function for modifyingroute variables before building a URL.
func (*Router)GetRoute¶
GetRoute returns a route registered with the given name. This methodwas renamed to Get() and remains here for backwards compatibility.
func (*Router)Handle¶
Handle registers a new route with a matcher for the URL path.See Route.Path() and Route.Handler().
func (*Router)HandleFunc¶
HandleFunc registers a new route with a matcher for the URL path.See Route.Path() and Route.HandlerFunc().
func (*Router)Headers¶
Headers registers a new route with a matcher for request header values.See Route.Headers().
func (*Router)Match¶
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 functionreturns true.
If the request does not match any of this router's or its subrouters' routesthen this function returns false. If available, a reason for the match failurewill 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 Handlerfield of the match argument.
func (*Router)MatcherFunc¶
func (r *Router) MatcherFunc(fMatcherFunc) *Route
MatcherFunc registers a new route with a custom matcher function.See Route.MatcherFunc().
func (*Router)Methods¶
Methods registers a new route with a matcher for HTTP methods.See Route.Methods().
func (*Router)PathPrefix¶
PathPrefix registers a new route with a matcher for the URL path prefix.See Route.PathPrefix().
func (*Router)Queries¶
Queries registers a new route with a matcher for URL query values.See Route.Queries().
func (*Router)Schemes¶
Schemes registers a new route with a matcher for URL schemes.See Route.Schemes().
func (*Router)ServeHTTP¶
func (r *Router) ServeHTTP(whttp.ResponseWriter, req *http.Request)
ServeHTTP dispatches the handler registered in the matched route.
When there is a match, the route variables can be retrieved callingmux.Vars(request).
func (*Router)SkipClean¶
SkipClean defines the path cleaning behaviour for new routes. The initialvalue 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 doubleslash. 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/ willbecome /fetch/http/xkcd.com/534
func (*Router)StrictSlash¶
StrictSlash defines the trailing slash behavior for new routes. The initialvalue is false.
When true, if the route path is "/path/", accessing "/path" will perform a redirectto the former and vice versa. In other words, your application will alwayssee the path as specified in the route.
When false, if the route path is "/path", accessing "/path/" will not matchthis route and vice versa.
The re-direct is a HTTP 301 (Moved Permanently). Note that when this is set forroutes with a non-idempotent method (e.g. POST, PUT), the subsequent re-directedrequest will be made as a GET by most clients. Use middleware or client settingsto 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'tbe determined from a prefix alone. However, any subrouters created from thatroute inherit the original StrictSlash setting.
func (*Router)Use¶added inv1.6.1
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)UseEncodedPath¶
UseEncodedPath tells the router to match the encoded original pathto 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"