Documentation
¶
Overview ¶
Package router wraps the standard library's net/http.ServeMux with nestable groups, per-group middleware, and typed handlers.
It builds on Go 1.22+ method+path patterns ("GET /widgets/{id}") and go-pkgz/routegroup for mountable sub-routers and group-scoped net/http middleware, then bridges the typed rest.HandlerFunc into the mux: HandleApp applies the router's application middleware plus any per-route middleware and encodes the returned Encoder via rest.Respond. Use it to assemble a service's routing tree; pair it with the mid package for standard middleware.
Usage ¶
r := router.New(errMapMid, authMid) // appMids applied to every HandleApp route
r.Use(mid.Panics(log), mid.AccessLog(log)) // net/http middleware (routegroup)
r.HandleApp("GET /healthz", health)
r.Route(func(r *router.Router) { // a nested, middleware-scoped group
api := r.Mount("/api/v1")
api.HandleApp("POST /widgets", createWidget, rateLimitMid)
api.HandleApp("GET /widgets/{id}", getWidget)
})
http.ListenAndServe(":8080", r) // *Router is an http.Handler
API ¶
- New(appMids ...rest.MidFunc): build a Router; appMids wrap every HandleApp route, outermost first (e.g. error mapping, auth).
- HandleApp(pattern, rest.HandlerFunc, mids ...rest.MidFunc): mount a typed handler; per-route mids are inside appMids, both adapted via rest.Respond.
- Mount(pattern): a sub-router rooted at a path prefix.
- Route(fn): register a nested group via a callback receiving a sub-router.
- With(mws ...Middleware): a sub-router with extra net/http middleware.
- Embedded *routegroup.Bundle methods (HandleFunc, Handle, Use, ...) remain available for raw net/http handlers.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Middleware ¶
Middleware is standard net/http middleware.
type Router ¶
type Router struct {
*routegroup.Bundle
// contains filtered or unexported fields
}
Router is a thin wrapper over routegroup.Bundle that additionally knows how to mount typed rest.HandlerFunc handlers. The zero value is not usable; use New.
func New ¶
New creates a Router backed by a fresh ServeMux. appMids are applied to every handler registered via HandleApp (e.g. error mapping, auth), outermost first.
func (*Router) HandleApp ¶
HandleApp registers a typed rest.HandlerFunc. The router's appMids plus any per-route mids are applied, and the result is adapted to http and encoded via rest.Respond.
func (*Router) With ¶
func (r *Router) With(mws ...Middleware) *Router
With returns a sub-router with the given net/http middleware applied.