go-router
Router on top of net/http's ServeMux with named routes, groups, mounts, host routing and middleware
About go-router
This large README is shown as a plain-text preview. Read the full README at the source
<p align="center">
<a href="https://docs.gowebthings.com/go-router">
<img src="./assets/go-router-logo.png" alt="go-router" height="70">
</a>
</p>
# go-router
[](https://pkg.go.dev/github.com/donseba/go-router)
[](https://codecov.io/gh/donseba/go-router)
[Documentation](https://docs.gowebthings.com/go-router) · Part of [go-webthings](https://gowebthings.com/components).
`go-router` is a lightweight router for Go websites and APIs. It builds on the standard library `net/http` `ServeMux` and adds the pieces most small and medium applications usually end up needing: route groups, middleware, named routes, host and subdomain routing, mounted routers, OpenAPI helpers, route walking, static files, and practical middleware.
It is designed for applications that want to stay close to `net/http` without giving up website/API ergonomics.
## Features
- Standard-library based routing with Go's method-aware `ServeMux` patterns.
- Route groups, middleware-only groups and per-route middleware.
- Exact host, subdomain, and wildcard subdomain routing.
- Named routes with reverse path and URL generation.
- Mounted routers that stay part of the router they are mounted on: route names, route walk, hosts and OpenAPI metadata, also when registered after `Mount`.
- Routers served at a prefix chosen per request (`ServeAt`), such as a module on a page whose address can change, with public paths for handlers, reverse routing (`For`, and `At` without a request) and `MatchedRoute`.
- Route walking and route table diagnostics.
- Static file and single-file serving, as named routes.
- Custom status handlers, with per-route and per-response opt-out, and `NotFound` and `MethodNotAllowed` handlers for unmatched requests only.
- Route lookup by method and path (`Match`), by path for any method (`Owns`), the route that served a request (`MatchedRoute`) and route labels (`MatchLabel`, `OwnsLabel`, `MatchedLabel`), with the mount for paths a mounted router has no route for, and paths the router redirects matched where the redirect leads.
- Middleware for routes and `NotFound` handlers (`Use`) and for every request (`UseAll`).
- Optional trailing slash redirects.
- OpenAPI metadata and schema helpers.
- JSON request/response helpers.
- Path parameter helper functions.
- Bundled middleware for request IDs, logging, request observation, recovery, timeouts, security and cache headers, CORS, real IP and request origin, gzip compression, ETags and `Last-Modified` checks, an output cache, rate limiting, body limits, content length and timing, logging through `log/slog`, with the standard library only.
- Registration freezes after the first request to avoid runtime mutation races.
## Install
```bash
go get github.com/donseba/go-router
```
`go-router` targets modern Go (its `go.mod` requires Go 1.23.1) and uses the standard library routing improvements introduced in Go 1.22.
## Quick Start
```go
package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/donseba/go-router"
"github.com/donseba/go-router/middleware"
)
func main() {
r := router.New(http.NewServeMux(), "Example API", "1.0.0")
r.Use(middleware.RequestID)
r.Use(middleware.Logger())
r.Use(middleware.Recover)
r.Use(middleware.Timeout(10 * time.Second))
r.Get("/", func(w http.ResponseWriter, req *http.Request) {
_, _ = fmt.Fprintln(w, "hello")
}).As("home")
r.Get("/users/{id}", func(w http.ResponseWriter, req *http.Request) {
id, err := router.IntParam(req, "id")
if err != nil {
_ = router.BadRequest(w, err)
return
}
_ = router.JSON(w, http.StatusOK, map[string]any{
"id": id,
})
}).As("users.show")
log.Fatal(http.ListenAndServe(":8080", r))
}
```
## Websites
`New` takes a `ServeMux` and an OpenAPI title and version; OpenAPI documentation stays off until `UseOpenapiDocs(true)` (see [OpenAPI](#openapi)). Websites can use `NewSite`, which creates its own `ServeMux`, needs no title or version and keeps OpenAPI documentation off. Its options set the handlers for unmatched requests (see [Not Found and Method Not Allowed](#not-found-and-method-not-allowed)):
```go
r := router.NewSite(
router.WithNotFound(http.HandlerFunc(notFound)),
router.WithMethodNotAllowed(http.HandlerFunc(notFound)),
)
r.RedirectTrailingSlash(true)
```
The router logs warnings, for example for route paths that could not be completed, and debug messages, to `slog.Default()`.
## Routing
Routes are registered by HTTP method:
```go
r.Get("/users", listUsers)
r.Post("/users", createUser)
r.Get("/users/{id}", showUser)
r.Put("/users/{id}", updateUser)
r.Patch("/users/{id}", patchUser)
r.Delete("/users/{id}", deleteUser)
r.Head("/health", healthHead)
r.Options("/health", healthOptions)
```
Route patterns use the standard `http.ServeMux` syntax:
```go
r.Get("/users/{id}", handler)
r.Get("/exact/{$}", handler)
r.Get("/assets/", handler)
```
Inside handlers, use standard `req.PathValue` or the small helper functions:
```go
id := req.PathValue("id")
intID, err := router.IntParam(req, "id")
```
`Handle` and `HandleFunc` register a handler for a `ServeMux` pattern, with or without a method, and return the route like the method functions do, so it can be named, labelled and get route middleware:
```go
r.Handle("/theme/", http.StripPrefix("/theme/", themeFiles)).As("theme").Label("asset")
r.Handle("PURGE /cache/", purge) // any method, also one of your own
```
Available helpers:
- `Param`
- `IntParam`
- `Int64Param`
- `BoolParam`
- `Float64Param`
## Error-Returning Registration
The normal registration API panics on duplicate routes or invalid late registration. That is useful during startup because mistakes fail loudly.
For apps that prefer explicit errors, use the `Try` variants:
```go
route, err := r.TryGet("/users/{id}", showUser)
if err != nil {
return err
}
if err := route.TryAs("users.show"); err != nil {
return err
}
```
Available `Try` methods:
- `TryGet`, `TryHead`, `TryPost`, `TryPut`, `TryPatch`, `TryDelete`, `TryOptions`
- `TryHandle`, `TryHandleFunc`
- `TryMount` (with the options of `Mount`)
- `TryUse` on a route (see [Route middleware](#route-middleware))
- `TryAs`, `TryLabel`
Their errors are a `router.RouteError`, whose `Err` holds what the panicking variant panics with.
For route paths, `RoutePathArgs` returns an error where `RoutePathWithParams` gives an empty or incomplete path (see [Named Routes and URLs](#named-routes-and-urls)).
The registering ones return the route, or the mount, as their panicking counterparts do, so it can be named, labelled and get middleware; it is `nil` when there is an error. Code that registers routes for others, such as the sections of an admin, can collect the errors instead of recovering panics:
```go
var errs []error
mount, err := r.TryMount("/admin", admin, router.AbsolutePaths())
if err != nil {
return err
}
errs = append(errs, mount.TryLabel("admin"))
route, err := r.TryGet("/admin/pages/{id}", editPage)
if err == nil {
errs = append(errs, route.TryUse(requireEditor), route.TryAs("admin.pages.edit"))
}
return errors.Join(append(errs, err)...)
```
`TryHandle`, `TryHandleFunc` and `TryMount` return the route next to the error since v0.12.0; they returned only the error before.
## Groups
Use `Group` to share a path prefix:
```go
r.Group("/api", func(api *router.Router) {
api.Get("/users", listUsers)
api.Post("/users", createUser)
})
```
Middleware added inside a group only applies to routes registered through that group:
```go
r.Group("/admin", func(admin *router.Router) {
admin.Use(adminOnly)
admin.Get("/dashboard", dashboard)
})
```
Use `With` for middleware-only groups:
```go
r.With(func(private *router.Router) {
private.Use(requireLogin)
private.Get("/account", account)
})
```
Group-level OpenAPI metadata is inherited by child routes:
```go
r.Group("/api", func(api *router.Router) {
api.UseDocs(router.Docs{
Tags: []string{"api"},
})
api.Get("/users", listUsers, router.Docs{
Summary: "List users",
})
})
```
## Host and Subdomain Routing
Scope routes to an exact host:
```go
r.Host("admin.example.com", func(admin *router.Router) {
admin.Get("/", adminHome)
})
```
Use `Subdomain` for named subdomains:
```go
r.Subdomain("app", "example.com", func(app *router.Router) {
app.Get("/", appHome)
})
```
Use `Subdomain("*", ...)` for wildcard subdomains:
```go
r.Subdomain("*", "example.com", func(tenant *router.Router) {
tenant.Get("/dashboard", tenantDashboard).As("tenant.dashboard")
})
```
`WildcardSubdomain("example.com", fn)` is the same as `Subdomain("*", "example.com", fn)`.
Exact hosts take precedence over wildcard hosts. The apex domain does not match a wildcard subdomain. Unknown hosts fall back to the default router.
## Named Routes and URLs
Name a route with `As`:
```go
r.Get("/users/{id}", showUser).As("users.show")
```
`As` returns the route, so calls chain: `r.Get("/users/{id}", showUser).As("users.show").Use(requireLogin)`.
Generate paths:
```go
path := r.RoutePathWithParams("users.show", map[string]any{
"id": 123,
})
// "/users/123"
```
Parameter values are URL-escaped:
```go
r.RoutePathWithParams("files.show", map[string]any{
"name": "hello world/a",
})
// "/files/hello%20world%2Fa"
```
Rest wildcards (`{name...}`) keep their slashes and escape each segment. The value is a string or a `[]string` of segments:
```go
r.Get("/docs/{path...}", showDoc).As("docs.show")
r.RoutePathWithParams("docs.show", map[string]any{
"path": "guides/getting started",
})
// "/docs/guides/getting%20started"
```
Reverse paths are the registered pattern without `{$}`, so a trailing slash is kept: `/admin/{$}` and `/admin/` are both `/admin/`, `/{$}` is `/`, and `/users` and `/users/` stay different routes. `RouteInfo.Path` holds this path and `RouteInfo.Pattern` the registered pattern.
`RoutePathWithParams` returns `""` for an unknown route and leaves a parameter without a value as its placeholder, reporting both to `slog.Default()`. Use `RoutePathArgs`, which takes the same map, to get an error instead and to add a query string:
```go
path, err := r.RoutePathArgs("users.show", map[string]any{
"id": 123,
}, url.Values{"tab": {"posts"}})
// "/users/123?tab=posts"
```
It returns an error wrapping `router.ErrUnknownRoute`, `router.ErrMissingParam` (no value, or an empty one for a `{name}` wildcard) or `router.ErrUnknownParam` (a parameter the route does not have).
Host routes can generate full URLs:
```go
r.Host("admin.example.com", func(admin *router.Router) {
admin.Get("/users/{id}", showUser).As("admin.users.show")
})
r.RouteURL("admin.users.show", map[string]any{"id": 123}, "https")
// "https://admin.example.com/users/123"
```
Wildcard subdomain URLs use a `subdomain` or `tenant` parameter:
```go
r.RouteURL("tenant.dashboard", map[string]any{
"subdomain": "acme",
}, "https")
// "https://acme.example.com/dashboard"
```
`RouteHost(name)` returns the host pattern of a route, such as `admin.example.com` or `*.example.com`, and `""` for a route without a host or an unknown route.
Template helpers are available through `FuncMap`:
```go
tmpl := template.New("page").Funcs(r.FuncMap())
```
`route` builds a path from key/value pairs, maps of parameters and `url.Values` for the query string. An unknown route or a missing or unknown parameter fails the template instead of rendering a broken link:
```html
<a href="{{ route "users.show" "id" .User.ID }}">Profile</a>
<a href="{{ route "search" .Query }}">Search</a>
<a href="{{ route "users.posts.show" .Params }}">Post</a>
```
The same function is available in Go as `RoutePathArgs`:
```go
path, err := r.RoutePathArgs("users.show", "id", 42, url.Values{"tab": {"posts"}})
// "/users/42?tab=posts"
```
Its method values, including those of `For(req)` and `At(prefix)`, are `router.PathFunc`s, so code that only builds links can take a `PathFunc` instead of a `*Router`.
Key/value pairs alone, and a single `map[string]any`, are read as they are, without building a map of parameters: a path costs one allocation, the string itself, also on a mounted router or one returned by `For` or `At`. Other arguments, such as `url.Values`, are combined into a map first.
Included template functions:
- `route`
- `hasRoute`, `routeOr`
- `routePath`
- `routePathWithParams`
- `routeHost`
- `routeURL`
- `isActiveRoute`
- `isActiveRouteExact`
- `isActiveRouteContains`
### Optional routes
A template can link to a route that may not exist, such as a route of an optional module, without an error or a warning. `hasRoute` reports whether a route exists, and `routeOr` gives the route's path or a fallback for an unknown route:
```html
{{ if hasRoute "news.index" }}<a href="{{ route "news.index" }}">News</a>{{ end }}
<a href="{{ routeOr "news.index" "/" }}">News</a>
<a href="{{ routeOr "news.show" "#" "id" .ID }}">Article</a>
```
`routeOr` takes the arguments of `route` after the fallback. Only an unknown route gives the fallback: a missing or unknown parameter of a route that exists still fails the template. In Go, use `HasRoute`.
### Active routes
`isActiveRoute` reports whether the current page is a route's path or below it, for navigation. It respects path segments: a route at `/admin/news` is active on `/admin/news` and `/admin/news/7/edit`, not on `/admin/newsletter`. A route whose path ends in a slash, such as `/admin/{$}`, is active on `/admin/` and below it. `isActiveRouteExact` leaves out the paths below the route:
```html
<a href="{{ route "admin.news" }}" {{ if isActiveRoute .Request "admin.news" }}aria-current="page"{{ end }}>News</a>
```
The current page is a `*url.URL`, a `url.URL`, an `*http.Request` (its URL) or a string with a path or URL, such as the page address an htmx request reports, so a template does not need a `*url.URL`. `isActiveRouteContains` takes the same.
The route's wildcards match any value, unless arguments, as for `route`, give theirs. Parameters left out still match any value, and a query string is ignored:
```html
{{ isActiveRoute .Request "users.show" }} <!-- /users/7, /users/8/posts -->
{{ isActiveRoute .Request "users.show" "id" 7 }} <!-- /users/7, /users/7/posts, not /users/8 -->
```
An unknown route is not active. Arguments that are not key value pairs or maps, and parameters the route does not have, fail the template. `IsActiveRoute` and `IsActiveRouteExact` are the Go functions.
## Mounting
Mount any `http.Handler` under a path:
```go
r.Mount("/debug", http.DefaultServeMux)
```
A handler that is not a `*router.Router` sees the path without the mount path, as with `http.StripPrefix`.
A mounted `*router.Router` becomes part of the router it is mounted on. Its routes, route names, hosts and OpenAPI paths and components show up there below the mount path, whether they were registered before or after `Mount`, until the first request freezes both:
```go
admin := router.NewSite()
r.Mount("/admin", admin)
admin.Get("/{$}", dashboard).As("admin.dashboard")
admin.Get("/users/{id}", showUser).As("admin.users.show")
r.RoutePath("admin.dashboard") // "/admin/"
r.RoutePathWithParams("admin.users.show", map[string]any{"id": 1}) // "/admin/users/1"
admin.RoutePath("admin.dashboard") // "/admin/"
```
Paths in a mounted router are public paths:
- Its handlers and middleware see the request URL as the outer router received it: `req.URL.Path` is `/admin/users/1`, not `/users/1`. Route patterns are matched below the mount path, and `req.PathValue` works as usual.
- Its reverse routing (`RoutePath`, `RoutePathWithParams`, `RoutePathArgs`, `RouteURL` and `FuncMap`) resolves through the outermost router it is mounted on, so it gives the same public paths, and can also build the paths of that router's other named routes. A router mounted more than once resolves through its first mount.
- `Routes`, `Walk` and `RouteTable` describe a router's own registrations: on the mounted router they are relative to it, on the router it is mounted on they are below the mount path.
A router can be mounted on several routers. Each of them resolves the mounted router's route names to its own mount path, but the mounted router itself resolves through its first mount only:
```go
first.Mount("/a", child)
second.Mount("/b", child)
child.RoutePath("child.home") // "/a/"
second.RoutePath("child.home") // "/b/"
```
To build the paths of another mount, ask the router it is mounted on. A router whose routes have names cannot be mounted twice on the same router, since route names are unique within a router, unless each mount has its own `NamePrefix` (see [Name prefixes](#name-prefixes)).
The mount path and the mount path with a trailing slash both reach the mounted router's `/` or `/{$}` route. Top-level OpenAPI fields of the mounted router (tags, security, security schemes) are taken over when it is mounted. A router cannot be mounted on itself or on a router mounted on it.
A mounted router's trailing slash redirects (`RedirectTrailingSlash`) go to the public path, `/admin/users/` to `/admin/users`, and so do the redirects of its `ServeMux` to a route with a trailing slash: with a route `/users/` in a router mounted at `/admin`, `/admin/users` redirects to `/admin/users/`, not to `/users/`.
`Mount` returns the mount as a route: it can be named (`RoutePath` gives the mount path with a trailing slash), get route middleware, which runs for every request of the mount, and labels, which a mounted router's routes get as well (see [Matching routes](#matching-routes)):
```go
r.Mount("/admin", admin).Use(requireLogin).Label("admin")
```
### Name prefixes
A router mounted more than once, such as one router per instance of a module, would register the same route names twice. `NamePrefix` puts a prefix before its names, as the router it is mounted on sees them:
```go
comments := router.NewSite()
comments.Post("/post", post).As("post")
r.Mount("/_/comments", comments, router.NamePrefix("comments."))
r.RoutePath("comments.post") // "/_/comments/post"
comments.RoutePath("post") // "/_/comments/post": its own names first
comments.RoutePath("home") // a name of r: the outer names without the prefix
```
### Routers with absolute paths and wrapped routers
A router whose patterns include the mount path already, such as one that registers its routes below a base path it is given, is mounted with `AbsolutePaths`. Requests at and below the mount path reach it unchanged, and its routes and names are taken over as they are:
```go
admin := router.NewSite()
admin.Group("/admin", func(routes *router.Router) {
routes.Get("/{$}", dashboard).As("admin.dashboard")
})
admin.RoutePath("admin.dashboard") // "/admin/", before and after the mount
r.Mount("/admin", admin, router.AbsolutePaths())
```
A handler with a `Router() *router.Router` method, such as a type that wraps its router in middleware of its own, is mounted as that router: its routes, names, hosts and docs become part of the router it is mounted on, and requests are served through the handler, which sees the full request URL. When it passes the request on to its router, the router matches below the mount path:
```go
type Admin struct{ router *router.Router }
func (a *Admin) Router() *router.Router { return a.router }
func (a *Admin) ServeHTTP(w http.ResponseWriter, req *http.Request) {
a.router.ServeHTTP(w, req.WithContext(withMessages(req.Context())))
}
r.Mount("/admin", admin) // routes relative to /admin
r.Mount("/admin", admin, router.AbsolutePaths()) // routes below /admin already
```
Frequently Asked Questions
What is go-router?
go-router is a Web Frameworks library for the Go programming language. Router on top of net/http's ServeMux with named routes, groups, mounts, host routing and middleware
How do I install go-router?
Install go-router with the Go module system using `go get donseba/go-router`. Check the repository for the current installation instructions.
What category does go-router belong to?
go-router is listed under Web Frameworks, specifically Routers.