What it is
gorilla/mux is a powerful URL router and dispatcher for Go, supporting matching on host, path, headers, query values and HTTP methods. It is part of the long-established Gorilla web toolkit.
mux matches requests on far more than the path: host, scheme, headers, query parameters, custom matcher functions and regular-expression path patterns. Routes can be named and used to build URLs in reverse.
Installation
go get -u github.com/gorilla/muxGetting started
The smallest useful thing you can do with it, and what each part means.
r := mux.NewRouter()
// Constrain the parameter with a regular expression.
r.HandleFunc("/books/{id:[0-9]+}", func(w http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
fmt.Fprintf(w, "book %s", vars["id"])
}).Methods(http.MethodGet)
http.ListenAndServe(":8080", r)r.HandleFunc("/books/{id}", getBook).Name("book")
url, err := r.Get("book").URL("id", "42")
if err == nil {
fmt.Println(url.String()) // /books/42
}Advanced usage
Where the library earns its place over a simpler alternative.
r := mux.NewRouter()
api := r.Host("api.{domain:.+}").Subrouter()
api.HandleFunc("/books", listBooks)
// Match only requests that accept JSON.
r.HandleFunc("/data", jsonHandler).
Headers("Accept", "application/json")
// Arbitrary matching logic.
r.MatcherFunc(func(req *http.Request, m *mux.RouteMatch) bool {
return req.Header.Get("X-Beta") == "1"
}).HandlerFunc(betaHandler)Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- Route unexpectedly returns 404
- Every matcher on the route must pass. A .Methods() or .Headers() constraint that does not match produces a 404, not a 405 — check the full chain.
- A general route shadows a specific one
- mux evaluates routes in the order they are registered. Register /books/new before /books/{id}.
Best practices
- Constrain path variables with regular expressions so invalid input is rejected by the router, not your handler.
- Name routes and build URLs in reverse rather than concatenating path strings.
- Register more specific routes before general ones — mux matches in registration order.
- For new projects, compare against chi or Go 1.22's standard router; mux is heavier than most services need.
Background
Why it exists, and what it was reacting to.
Gorilla was one of Go's earliest web toolkits and mux its best-known component. The project was archived in 2022 and then revived in 2023 under new maintainers after significant community response — a reminder to check maintenance status before adopting infrastructure.
