Documentation
¶
Overview ¶
Package router provides route grouping and method helpers on top of http.ServeMux.
It adds .Get()/.Post() method helpers, Group(prefix, ...middleware) for prefix grouping, and per-group middleware — all delegating to a single http.ServeMux underneath.
Usage:
r := router.New()
r.Use(middleware.RequestID(), middleware.Logger(logger))
r.Get("/health", healthHandler)
api := r.Group("/api/v1", authMiddleware)
api.Get("/users", listUsers)
api.Post("/users", createUser)
srv := server.New(r) // router implements http.Handler
Index ¶
- func DefaultErrorHandler(w http.ResponseWriter, _ *http.Request, err error)
- type ErrorHandler
- type Group
- func (g *Group) Delete(pattern string, fn HandlerFunc) *RouteEntry
- func (g *Group) DeleteFunc(pattern string, fn http.HandlerFunc) *RouteEntry
- func (g *Group) File(pattern, filePath string)
- func (g *Group) Get(pattern string, fn HandlerFunc) *RouteEntry
- func (g *Group) GetFunc(pattern string, fn http.HandlerFunc) *RouteEntry
- func (g *Group) Group(prefix string, mw ...middleware.Middleware) *Group
- func (g *Group) Handle(pattern string, handler http.Handler) *RouteEntry
- func (g *Group) HandleFunc(pattern string, fn http.HandlerFunc) *RouteEntry
- func (g *Group) Head(pattern string, fn HandlerFunc) *RouteEntry
- func (g *Group) HeadFunc(pattern string, fn http.HandlerFunc) *RouteEntry
- func (g *Group) Mount(prefix string, handler http.Handler)
- func (g *Group) Options(pattern string, fn HandlerFunc) *RouteEntry
- func (g *Group) OptionsFunc(pattern string, fn http.HandlerFunc) *RouteEntry
- func (g *Group) Patch(pattern string, fn HandlerFunc) *RouteEntry
- func (g *Group) PatchFunc(pattern string, fn http.HandlerFunc) *RouteEntry
- func (g *Group) Post(pattern string, fn HandlerFunc) *RouteEntry
- func (g *Group) PostFunc(pattern string, fn http.HandlerFunc) *RouteEntry
- func (g *Group) Put(pattern string, fn HandlerFunc) *RouteEntry
- func (g *Group) PutFunc(pattern string, fn http.HandlerFunc) *RouteEntry
- func (g *Group) Route(prefix string, fn func(*Group), mw ...middleware.Middleware) *Group
- func (g *Group) Static(prefix, dir string)
- func (g *Group) Use(mw ...middleware.Middleware)
- func (g *Group) With(mw ...middleware.Middleware) *Group
- type HandlerFunc
- type Option
- type ParamConstraint
- type RouteEntry
- type RouteInfo
- type Router
- func (r *Router) Delete(pattern string, fn HandlerFunc) *RouteEntry
- func (r *Router) DeleteFunc(pattern string, fn http.HandlerFunc) *RouteEntry
- func (r *Router) File(pattern, filePath string)
- func (r *Router) Get(pattern string, fn HandlerFunc) *RouteEntry
- func (r *Router) GetFunc(pattern string, fn http.HandlerFunc) *RouteEntry
- func (r *Router) Group(prefix string, mw ...middleware.Middleware) *Group
- func (r *Router) Handle(pattern string, handler http.Handler) *RouteEntry
- func (r *Router) HandleFunc(pattern string, fn http.HandlerFunc) *RouteEntry
- func (r *Router) Head(pattern string, fn HandlerFunc) *RouteEntry
- func (r *Router) HeadFunc(pattern string, fn http.HandlerFunc) *RouteEntry
- func (r *Router) Mount(prefix string, handler http.Handler)
- func (r *Router) Options(pattern string, fn HandlerFunc) *RouteEntry
- func (r *Router) OptionsFunc(pattern string, fn http.HandlerFunc) *RouteEntry
- func (r *Router) Patch(pattern string, fn HandlerFunc) *RouteEntry
- func (r *Router) PatchFunc(pattern string, fn http.HandlerFunc) *RouteEntry
- func (r *Router) Post(pattern string, fn HandlerFunc) *RouteEntry
- func (r *Router) PostFunc(pattern string, fn http.HandlerFunc) *RouteEntry
- func (r *Router) Put(pattern string, fn HandlerFunc) *RouteEntry
- func (r *Router) PutFunc(pattern string, fn http.HandlerFunc) *RouteEntry
- func (r *Router) Route(prefix string, fn func(*Group), mw ...middleware.Middleware) *Group
- func (r *Router) Routes() []RouteInfo
- func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (r *Router) Static(prefix, dir string)
- func (r *Router) URL(name string, params ...string) string
- func (r *Router) Use(mw ...middleware.Middleware)
- func (r *Router) Walk(fn func(RouteInfo) error) error
- func (r *Router) With(mw ...middleware.Middleware) *Group
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DefaultErrorHandler ¶
func DefaultErrorHandler(w http.ResponseWriter, _ *http.Request, err error)
DefaultErrorHandler writes a JSON error response matching the standard envelope format. It uses errors.As to extract *errors.Error; unrecognized errors become 500 Internal Server Error.
Types ¶
type ErrorHandler ¶
type ErrorHandler func(http.ResponseWriter, *http.Request, error)
ErrorHandler handles errors returned by HandlerFunc handlers.
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
Group represents a collection of routes that share a common prefix and middleware.
func (*Group) Delete ¶
func (g *Group) Delete(pattern string, fn HandlerFunc) *RouteEntry
Delete registers an error-returning handler for DELETE requests.
func (*Group) DeleteFunc ¶
func (g *Group) DeleteFunc(pattern string, fn http.HandlerFunc) *RouteEntry
DeleteFunc registers a standard http.HandlerFunc for DELETE requests.
func (*Group) File ¶ added in v0.16.0
File registers a handler that serves a single file for GET requests.
r.File("/favicon.ico", "./public/favicon.ico")
func (*Group) Get ¶
func (g *Group) Get(pattern string, fn HandlerFunc) *RouteEntry
Get registers an error-returning handler for GET requests.
func (*Group) GetFunc ¶
func (g *Group) GetFunc(pattern string, fn http.HandlerFunc) *RouteEntry
GetFunc registers a standard http.HandlerFunc for GET requests.
func (*Group) Group ¶
func (g *Group) Group(prefix string, mw ...middleware.Middleware) *Group
Group creates a child group with the given prefix and optional middleware.
func (*Group) Handle ¶
func (g *Group) Handle(pattern string, handler http.Handler) *RouteEntry
Handle registers an http.Handler for the given pattern. The pattern may include a method prefix (e.g. "GET /path").
func (*Group) HandleFunc ¶
func (g *Group) HandleFunc(pattern string, fn http.HandlerFunc) *RouteEntry
HandleFunc registers an http.HandlerFunc for the given pattern. The pattern may include a method prefix (e.g. "GET /path").
func (*Group) Head ¶ added in v0.12.0
func (g *Group) Head(pattern string, fn HandlerFunc) *RouteEntry
Head registers an error-returning handler for HEAD requests.
func (*Group) HeadFunc ¶ added in v0.12.0
func (g *Group) HeadFunc(pattern string, fn http.HandlerFunc) *RouteEntry
HeadFunc registers a standard http.HandlerFunc for HEAD requests.
func (*Group) Mount ¶ added in v0.16.0
Mount attaches an http.Handler at the given prefix, stripping the prefix from the request path before passing it to the handler. Group middleware is applied. If the handler is a *Router, its routes are merged into the parent's route table for introspection.
admin := router.New()
admin.Get("/stats", statsHandler)
r.Mount("/admin", admin)
func (*Group) Options ¶ added in v0.12.0
func (g *Group) Options(pattern string, fn HandlerFunc) *RouteEntry
Options registers an error-returning handler for OPTIONS requests.
func (*Group) OptionsFunc ¶ added in v0.12.0
func (g *Group) OptionsFunc(pattern string, fn http.HandlerFunc) *RouteEntry
OptionsFunc registers a standard http.HandlerFunc for OPTIONS requests.
func (*Group) Patch ¶
func (g *Group) Patch(pattern string, fn HandlerFunc) *RouteEntry
Patch registers an error-returning handler for PATCH requests.
func (*Group) PatchFunc ¶
func (g *Group) PatchFunc(pattern string, fn http.HandlerFunc) *RouteEntry
PatchFunc registers a standard http.HandlerFunc for PATCH requests.
func (*Group) Post ¶
func (g *Group) Post(pattern string, fn HandlerFunc) *RouteEntry
Post registers an error-returning handler for POST requests.
func (*Group) PostFunc ¶
func (g *Group) PostFunc(pattern string, fn http.HandlerFunc) *RouteEntry
PostFunc registers a standard http.HandlerFunc for POST requests.
func (*Group) Put ¶
func (g *Group) Put(pattern string, fn HandlerFunc) *RouteEntry
Put registers an error-returning handler for PUT requests.
func (*Group) PutFunc ¶
func (g *Group) PutFunc(pattern string, fn http.HandlerFunc) *RouteEntry
PutFunc registers a standard http.HandlerFunc for PUT requests.
func (*Group) Route ¶ added in v0.16.0
func (g *Group) Route(prefix string, fn func(*Group), mw ...middleware.Middleware) *Group
Route creates a child group with the given prefix and optional middleware, then calls fn to register routes on it. This is syntactic sugar for inline sub-routing:
r.Route("/users", func(sub *Group) {
sub.Get("/", listUsers)
sub.Get("/{id}", getUser)
})
func (*Group) Static ¶ added in v0.16.0
Static serves files from the given filesystem directory under the URL prefix. Group middleware is applied to all requests.
r.Static("/assets", "./public")
func (*Group) Use ¶
func (g *Group) Use(mw ...middleware.Middleware)
Use appends middleware to this group. Middleware added via Use only applies to routes registered after the call.
func (*Group) With ¶ added in v0.16.0
func (g *Group) With(mw ...middleware.Middleware) *Group
With returns a child group that shares this group's prefix but adds the given middleware. It is intended for per-route middleware:
r.With(authMW).Get("/admin", adminHandler)
type HandlerFunc ¶
type HandlerFunc func(http.ResponseWriter, *http.Request) error
HandlerFunc is an HTTP handler that returns an error. Errors are handled by the router's ErrorHandler.
func ValidateParams ¶ added in v0.16.0
func ValidateParams(fn HandlerFunc, constraints ...ParamConstraint) HandlerFunc
ValidateParams wraps a HandlerFunc with path parameter validation. Constraints are checked in order before the handler is called. On the first failure, it returns errors.BadRequest with the constraint's ErrMessage.
type Option ¶
type Option func(*Router)
Option configures a Router.
func WithErrorHandler ¶
func WithErrorHandler(fn ErrorHandler) Option
WithErrorHandler sets a custom error handler for the router.
func WithMethodNotAllowed ¶ added in v0.16.0
WithMethodNotAllowed sets a custom handler for 405 Method Not Allowed responses. When set, this handler is called instead of the ErrorHandler for disallowed methods.
func WithNotFound ¶ added in v0.16.0
WithNotFound sets a custom handler for 404 Not Found responses. When set, this handler is called instead of the ErrorHandler for unmatched routes.
func WithRedirectSlash ¶ added in v0.16.0
func WithRedirectSlash() Option
WithRedirectSlash sends a 301 Moved Permanently redirect for requests with a trailing slash. "/users/" redirects to "/users". The root path "/" is never redirected. Mutually exclusive with WithStripSlash.
func WithStripSlash ¶ added in v0.16.0
func WithStripSlash() Option
WithStripSlash silently removes trailing slashes from request paths before routing. "/users/" becomes "/users". The root path "/" is never modified.
type ParamConstraint ¶ added in v0.16.0
type ParamConstraint struct {
Name string // path parameter name (must match {name} in the pattern)
Validate func(string) bool // returns true if the value is valid
ErrMessage string // message for the BadRequest error on failure
}
ParamConstraint defines a validation rule for a single path parameter.
func Int ¶ added in v0.16.0
func Int(name string) ParamConstraint
Int returns a constraint that requires the parameter to be a valid integer.
func OneOf ¶ added in v0.16.0
func OneOf(name string, values ...string) ParamConstraint
OneOf returns a constraint that requires the parameter to be one of the allowed values.
func Regex ¶ added in v0.16.0
func Regex(name string, pattern string) ParamConstraint
Regex returns a constraint that requires the parameter to match the given regular expression. It panics if the pattern is not a valid regular expression.
func UUID ¶ added in v0.16.0
func UUID(name string) ParamConstraint
UUID returns a constraint that requires the parameter to be a valid UUID.
type RouteEntry ¶ added in v0.16.0
type RouteEntry struct {
// contains filtered or unexported fields
}
RouteEntry is returned by route registration methods to allow optional chaining. Callers that ignore the return value get the same behavior as before.
func (*RouteEntry) Name ¶ added in v0.16.0
func (re *RouteEntry) Name(name string) *RouteEntry
Name assigns a name to this route for URL generation. It panics if the name is already taken (fail-fast, like http.ServeMux on duplicate patterns).
type RouteInfo ¶ added in v0.16.0
type RouteInfo struct {
Method string // HTTP method ("GET", "POST", etc.). Empty for method-agnostic Handle() routes.
Pattern string // Full path pattern as registered, e.g. "/api/v1/users/{id}".
Name string // Optional name set via RouteEntry.Name(), used for URL generation.
HandlerName string // Runtime function name of the original handler.
}
RouteInfo holds metadata about a registered route.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router is a thin wrapper around http.ServeMux that provides method helpers, route grouping, and per-group middleware.
func (*Router) Delete ¶
func (r *Router) Delete(pattern string, fn HandlerFunc) *RouteEntry
Delete registers an error-returning handler for DELETE requests.
func (*Router) DeleteFunc ¶
func (r *Router) DeleteFunc(pattern string, fn http.HandlerFunc) *RouteEntry
DeleteFunc registers a standard http.HandlerFunc for DELETE requests.
func (*Router) File ¶ added in v0.16.0
File registers a handler that serves a single file for GET requests.
func (*Router) Get ¶
func (r *Router) Get(pattern string, fn HandlerFunc) *RouteEntry
Get registers an error-returning handler for GET requests.
func (*Router) GetFunc ¶
func (r *Router) GetFunc(pattern string, fn http.HandlerFunc) *RouteEntry
GetFunc registers a standard http.HandlerFunc for GET requests.
func (*Router) Group ¶
func (r *Router) Group(prefix string, mw ...middleware.Middleware) *Group
Group creates a new route group with the given prefix and optional middleware.
func (*Router) Handle ¶
func (r *Router) Handle(pattern string, handler http.Handler) *RouteEntry
Handle registers an http.Handler for the given pattern.
func (*Router) HandleFunc ¶
func (r *Router) HandleFunc(pattern string, fn http.HandlerFunc) *RouteEntry
HandleFunc registers an http.HandlerFunc for the given pattern.
func (*Router) Head ¶ added in v0.12.0
func (r *Router) Head(pattern string, fn HandlerFunc) *RouteEntry
Head registers an error-returning handler for HEAD requests.
func (*Router) HeadFunc ¶ added in v0.12.0
func (r *Router) HeadFunc(pattern string, fn http.HandlerFunc) *RouteEntry
HeadFunc registers a standard http.HandlerFunc for HEAD requests.
func (*Router) Options ¶ added in v0.12.0
func (r *Router) Options(pattern string, fn HandlerFunc) *RouteEntry
Options registers an error-returning handler for OPTIONS requests.
func (*Router) OptionsFunc ¶ added in v0.12.0
func (r *Router) OptionsFunc(pattern string, fn http.HandlerFunc) *RouteEntry
OptionsFunc registers a standard http.HandlerFunc for OPTIONS requests.
func (*Router) Patch ¶
func (r *Router) Patch(pattern string, fn HandlerFunc) *RouteEntry
Patch registers an error-returning handler for PATCH requests.
func (*Router) PatchFunc ¶
func (r *Router) PatchFunc(pattern string, fn http.HandlerFunc) *RouteEntry
PatchFunc registers a standard http.HandlerFunc for PATCH requests.
func (*Router) Post ¶
func (r *Router) Post(pattern string, fn HandlerFunc) *RouteEntry
Post registers an error-returning handler for POST requests.
func (*Router) PostFunc ¶
func (r *Router) PostFunc(pattern string, fn http.HandlerFunc) *RouteEntry
PostFunc registers a standard http.HandlerFunc for POST requests.
func (*Router) Put ¶
func (r *Router) Put(pattern string, fn HandlerFunc) *RouteEntry
Put registers an error-returning handler for PUT requests.
func (*Router) PutFunc ¶
func (r *Router) PutFunc(pattern string, fn http.HandlerFunc) *RouteEntry
PutFunc registers a standard http.HandlerFunc for PUT requests.
func (*Router) Route ¶ added in v0.16.0
func (r *Router) Route(prefix string, fn func(*Group), mw ...middleware.Middleware) *Group
Route creates a sub-group with the given prefix and calls fn to register routes on it.
func (*Router) Routes ¶ added in v0.16.0
Routes returns a copy of all registered routes. The returned slice is a snapshot; modifying it has no effect on the router.
func (*Router) ServeHTTP ¶
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
ServeHTTP implements http.Handler. It intercepts 404 and 405 responses from the underlying ServeMux and routes them through the router's ErrorHandler for consistent error format.
func (*Router) Static ¶ added in v0.16.0
Static serves files from the given directory under the URL prefix.
func (*Router) URL ¶ added in v0.16.0
URL builds a URL path for the named route, substituting path parameters. Parameters are provided as key-value pairs: r.URL("get-user", "id", "42") returns "/users/42".
It panics if the route name is not found, if the number of params is odd, if a {placeholder} in the pattern has no matching key in params, or if extra params are provided that don't match any placeholder.
func (*Router) Use ¶
func (r *Router) Use(mw ...middleware.Middleware)
Use adds middleware to the root group.
func (*Router) Walk ¶ added in v0.16.0
Walk iterates over all registered routes in registration order, calling fn for each. If fn returns a non-nil error, Walk stops and returns that error.
func (*Router) With ¶ added in v0.16.0
func (r *Router) With(mw ...middleware.Middleware) *Group
With returns a group that shares the root prefix but adds the given middleware for the next registered route(s).