On this page

Groups and Sub-Routers

Groups allow you to organize routes that share a common URL prefix and/or a common set of middleware. Sub-routers extend this further by allowing completely independent *Mux instances to be mounted at a path.

Table of Contents


Creating a Group

Group returns a *Group that shares the parent *Mux and prepends a path prefix to every route:

mux := muxmaster.New()

api := mux.Group("/api/v1")
api.GET("/users", listUsers)      // → GET /api/v1/users
api.POST("/users", createUser)    // → POST /api/v1/users
api.GET("/users/:id", getUser)    // → GET /api/v1/users/:id

The group shares the same underlying tree as the parent router. Routes are registered directly into the parent mux with the full prefix prepended.

The prefix and the route path are joined with a single /: mux.Group("/api/") followed by GET("/users", …) registers /api/users, not /api//users. Nothing else is inserted or removed — mux.Group("/api") with GET("users", …) would produce /apiusers, so start route paths with /. The same join applies to sub-group prefixes, Group.Mount and Group.ServeFiles.


Group Middleware

Middleware applied to a group wraps only the routes of that group. Mux-level Use middleware wraps the group middleware, so it runs first:

mux := muxmaster.New()
mux.Use(middleware.Logger(os.Stdout)) // applied to every route

api := mux.Group("/api/v1")
api.Use(requireAPIKey)              // applied only to /api/v1/* routes

api.GET("/users", listUsers)
// request path: Logger → requireAPIKey → listUsers

mux.GET("/health", health)
// request path: Logger → health (no requireAPIKey)

Important: call Use before registering routes on the group, for the same reason it must be called before routes on the mux.

Group Use middleware does not wrap fast routes: group.HandleFast panics if the group has Use middleware. Use group.UseFast for FastMiddleware, or mux.Pre for policy that must cover every route.


Nested Groups

Groups can be nested to any depth. Each level adds its prefix and optionally its own middleware:

api := mux.Group("/api/v1")
api.Use(requireAPIKey)

// Sub-group for admin endpoints
admin := api.Group("/admin")
admin.Use(requireAdmin)

admin.GET("/stats", getStats)        // GET /api/v1/admin/stats
admin.DELETE("/users/:id", deleteUser) // DELETE /api/v1/admin/users/:id

A sub-group starts with a copy of its parent's middleware. Middleware added to either group afterwards does not affect the other.


Inline Groups with Route

Route creates a sub-group and calls a closure with it. This is equivalent to calling Group manually, but keeps related routes visually grouped in the source code:

mux.Route("/api/v1", func(api *muxmaster.Group) {
    api.Use(requireAPIKey)

    api.GET("/users", listUsers)
    api.POST("/users", createUser)

    api.Route("/admin", func(admin *muxmaster.Group) {
        admin.Use(requireAdmin)
        admin.DELETE("/users/:id", deleteUser)
        admin.GET("/stats", getStats)
    })
})

Groups can also call Route on themselves:

api := mux.Group("/api/v1")
api.Route("/reports", func(g *muxmaster.Group) {
    g.GET("/daily", dailyReport)
    g.GET("/weekly", weeklyReport)
})

Scoped Middleware with With

With returns a new group with additional middleware appended, without modifying the original group. It is useful for applying middleware to a single route:

api := mux.Group("/api/v1")

// deleteUser is wrapped by both api's middleware and requireAdmin
api.With(requireAdmin).DELETE("/users/:id", deleteUser)

// processPayment is wrapped by both api's middleware and rateLimit + auditLog
api.With(rateLimit, auditLog).POST("/payments", processPayment)

// listUsers uses only api's middleware
api.GET("/users", listUsers)

Mounting Sub-Routers

Mount attaches a separate http.Handler at a path prefix. The prefix is stripped from the request URL before it is forwarded to the mounted handler. This allows independently built routers to be composed:

// Version 2 router — built and tested independently
v2 := muxmaster.New()
v2.GET("/users", listUsersV2)
v2.POST("/users", createUserV2)

// Attach to the main router
mux.Mount("/v2", v2)
// GET /v2/users → v2 sees GET /users

The mounted handler receives r.URL.Path with the prefix stripped, so a sub-router mounted at /v2 sees /users, not /v2/users. A request for /v2/ reaches it as /, and a request for the bare prefix /v2 is redirected to /v2/ when RedirectTrailingSlash is true.

How a mount is registered: trailing slashes are removed from the prefix, and the mount is registered under the internal method "*" with the pattern <prefix>/*mux_mount; Routes() lists it that way. The mount receives requests of every method, including methods the router does not support for normal routes. A route registered for the request's method takes precedence over the mount: with GET /v2/health registered on mux, a GET for that path never reaches v2, while a POST for it does. The prefix may contain parameters, but its last element must not be an optional parameter (that panics).

Middleware: Use middleware registered on mux before the Mount call wraps the mounted handler and sees the original, unstripped request, as does Pre middleware.

Request handling:

Before forwarding to the mounted handler, MuxMaster creates a shallow request copy — a new *http.Request that shares the header map and context with the original, but carries a new *url.URL with the stripped Path (and RawPath, when it can be stripped consistently). The original request passed to ServeHTTP is never modified. The forwarded request does not carry the original path; if the mounted handler needs it, read it in middleware registered before Mount.

Redirects from a mounted *Mux: when the mounted handler is itself a *muxmaster.Mux, its own trailing-slash and fixed-path redirects keep the mount prefix — v2's redirect from /users/ to /users reaches the client as Location: /v2/users. Redirects that your own code issues (for example with http.Redirect) are not rewritten.

Organizing a large application

func main() {
    mux := muxmaster.New()
    mux.Use(middleware.Logger(os.Stdout))
    mux.Use(middleware.RecovererWithLogger(slog.Default()))

    mux.Mount("/api/v1", newV1Router())
    mux.Mount("/api/v2", newV2Router())
    mux.Mount("/admin",  newAdminRouter())

    log.Fatal(http.ListenAndServe(":8080", mux))
}

func newV1Router() http.Handler {
    mux := muxmaster.New()
    mux.Use(requireAPIKey)
    mux.GET("/users", listUsers)
    mux.POST("/users", createUser)
    return mux
}

Mounting on a Group

Mount is also available on *Group, which combines the group's prefix with the mount prefix. The group's Use middleware wraps the mounted handler, so a group protected by an authentication middleware also protects what is mounted on it:

api := mux.Group("/api")
v1 := muxmaster.New()
v1.GET("/users", listUsers)

api.Mount("/v1", v1)
// GET /api/v1/users → handled by listUsers

Serving Static Files from a Group

ServeFiles on a group prepends the group prefix:

assets := mux.Group("/static")
assets.ServeFiles("/*filepath", http.Dir("./public"))
// GET /static/css/main.css → ./public/css/main.css

ServeFiles registers GET and HEAD routes and serves them with http.FileServer, which cleans the path, so .. segments cannot escape the root. The prefix must end with /*name; ServeFiles panics otherwise, or if the root is nil.


Design Patterns

API versioning

v1 := mux.Group("/api/v1")
v2 := mux.Group("/api/v2")

v1.GET("/users", listUsersV1)
v2.GET("/users", listUsersV2)

Feature-based organization

Group by feature domain rather than by HTTP method:

mux.Route("/api/v1", func(api *muxmaster.Group) {
    api.Use(requireAPIKey)

    // Users domain
    api.Route("/users", func(g *muxmaster.Group) {
        g.GET("", listUsers)
        g.POST("", createUser)
        g.GET("/:id", getUser)
        g.PUT("/:id", updateUser)
        g.DELETE("/:id", deleteUser)
    })

    // Orders domain
    api.Route("/orders", func(g *muxmaster.Group) {
        g.GET("", listOrders)
        g.POST("", createOrder)
        g.GET("/:id", getOrder)
    })
})

Micro-service composition

Mount independent services behind a reverse proxy router:

mux := muxmaster.New()
trustedProxy := netip.MustParsePrefix("10.0.0.0/8")
mux.Use(middleware.RealIP(&trustedProxy))
mux.Use(middleware.RequestID())

mux.Mount("/auth",    authService)
mux.Mount("/catalog", catalogService)
mux.Mount("/orders",  orderService)
mux.Mount("/payment", paymentService)

See Also

  • Middleware — middleware scopes and composition
  • Routing — pattern syntax and conflict resolution
  • Cookbook — application structure recipes

Common questions

How do I group routes that share a path prefix?

Call mux.Group("/api/v1") and register routes on the returned *Group; each route gets the prefix, so api.GET("/users", h) registers GET /api/v1/users.

The prefix and the route path are joined with a single /, so mux.Group("/api/") followed by GET("/users", h) also registers /api/users.

How do I apply middleware to only the routes of a group?

Call group.Use(mw) before registering the group's routes; the middleware wraps only those routes.

Mux-level Use middleware still wraps group routes and runs first. group.With(mw) returns a copy of the group with extra middleware, which is useful for a single route.

How do I attach an independent router under a prefix?

Call mux.Mount("/v2", sub), which forwards every request under /v2 to sub with the prefix stripped from r.URL.Path.

The mounted handler can be any http.Handler, including another *muxmaster.Mux. A route registered on the outer router for the request's method takes precedence over the mount, and a request for the bare prefix /v2 is redirected to /v2/ when RedirectTrailingSlash is true.

Upstream source

This page mirrors docs/groups.md at the v1.3.0 tag. The behaviour it describes is implemented in group.go, mux.go.