Documentation
¶
Index ¶
- Constants
- Variables
- func AllMethods() []string
- func AnyMethods() []string
- func Debug(val bool)
- func HandleFallbackRoute(r *Router)
- func HandleMethodNotAllowed(r *Router)
- func InterceptAll(path string) func(*Router)
- func IsDebug() bool
- func MethodsString() string
- func StrictLastSlash(r *Router)
- func UseEncodedPath(r *Router)
- func WithEncodedPath(on bool) func(*Router)
- func WithFallbackRoute(on bool) func(*Router)
- func WithMethodNotAllowed(on bool) func(*Router)
- func WithStrictLastSlash(on bool) func(*Router)
- type BuildRequestURL
- func (b *BuildRequestURL) Build(withParams ...M) *url.URL
- func (b *BuildRequestURL) Host(host string) *BuildRequestURL
- func (b *BuildRequestURL) Params(params M) *BuildRequestURL
- func (b *BuildRequestURL) Path(path string) *BuildRequestURL
- func (b *BuildRequestURL) Queries(queries url.Values) *BuildRequestURL
- func (b *BuildRequestURL) Scheme(scheme string) *BuildRequestURL
- func (b *BuildRequestURL) User(username, password string) *BuildRequestURL
- type Context
- func (c *Context) Abort()
- func (c *Context) AbortThen() *Context
- func (c *Context) AbortWithStatus(status int, msg ...string)
- func (c *Context) AddError(err error)
- func (c *Context) Attachment(srcFile, outName string)
- func (c *Context) AutoBind(obj any) error
- func (c *Context) Back(optionalCode ...int)
- func (c *Context) Binary(status int, in io.ReadSeeker, outName string, inline bool)
- func (c *Context) Bind(obj any) error
- func (c *Context) BindForm(obj any) error
- func (c *Context) BindJSON(obj any) error
- func (c *Context) BindXML(obj any) error
- func (c *Context) Blob(status int, contentType string, data []byte)
- func (c *Context) ClientIP() string
- func (c *Context) Cookie(name string) string
- func (c *Context) DelCookie(names ...string)
- func (c *Context) Err() error
- func (c *Context) FastSetCookie(name, value string, maxAge int, opts ...func(*http.Cookie))
- func (c *Context) File(filePath string)
- func (c *Context) FileContent(file string, names ...string)
- func (c *Context) FirstError() error
- func (c *Context) Get(key string) (any, bool)
- func (c *Context) HTML(status int, data []byte)
- func (c *Context) HTMLString(status int, data string)
- func (c *Context) HTTPError(msg string, status int)
- func (c *Context) Header(key string) string
- func (c *Context) Init(w http.ResponseWriter, req *http.Request)
- func (c *Context) Inline(srcFile, outName string)
- func (c *Context) IsAborted() bool
- func (c *Context) JSON(status int, obj any)
- func (c *Context) JSONBytes(status int, bs []byte)
- func (c *Context) JSONP(status int, callback string, obj any)
- func (c *Context) Length() int
- func (c *Context) MatchedPath() string
- func (c *Context) MustBind(obj any, binder binding.Binder)
- func (c *Context) MustRender(status int, obj any, renderer render.Renderer)
- func (c *Context) Next()
- func (c *Context) NoContent()
- func (c *Context) Param(name string) string
- func (c *Context) Params() *Params
- func (c *Context) Query(key string, defVal ...string) string
- func (c *Context) Redirect(path string, optionalCode ...int)
- func (c *Context) Render(status int, name string, data any) (err error)
- func (c *Context) ReqCtxValue(key any) any
- func (c *Context) Respond(status int, obj any, renderer render.Renderer)
- func (c *Context) Route() *Route
- func (c *Context) Router() *Router
- func (c *Context) SafeGet(key string) any
- func (c *Context) Set(key string, value any)
- func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)
- func (c *Context) SetHandlers(chain HandlersChain)
- func (c *Context) SetHeader(key, value string)
- func (c *Context) SetStatus(status int)
- func (c *Context) ShouldBind(obj any, binder binding.Binder) error
- func (c *Context) ShouldRender(status int, obj any, renderer render.Renderer) error
- func (c *Context) StatusCode() int
- func (c *Context) Stream(status int, contentType string, r io.Reader)
- func (c *Context) Text(status int, str string)
- func (c *Context) URL() *url.URL
- func (c *Context) Validate(obj any) error
- func (c *Context) WriteBytes(bt []byte)
- func (c *Context) WriteString(str string)
- func (c *Context) XML(status int, obj any, indents ...string)
- type ControllerFace
- type Group
- func (g *Group) Add(path string, h HandlerFunc, methods ...string) *Route
- func (g *Group) AddNamed(name, path string, h HandlerFunc, methods ...string) *Route
- func (g *Group) Any(path string, h HandlerFunc, mw ...HandlerFunc) *Route
- func (g *Group) CONNECT(path string, h HandlerFunc, mw ...HandlerFunc) *Route
- func (g *Group) DELETE(path string, h HandlerFunc, mw ...HandlerFunc) *Route
- func (g *Group) GET(path string, h HandlerFunc, mw ...HandlerFunc) *Route
- func (g *Group) HEAD(path string, h HandlerFunc, mw ...HandlerFunc) *Route
- func (g *Group) NewGroup(prefix string, middles ...HandlerFunc) *Group
- func (g *Group) OPTIONS(path string, h HandlerFunc, mw ...HandlerFunc) *Route
- func (g *Group) PATCH(path string, h HandlerFunc, mw ...HandlerFunc) *Route
- func (g *Group) POST(path string, h HandlerFunc, mw ...HandlerFunc) *Route
- func (g *Group) PUT(path string, h HandlerFunc, mw ...HandlerFunc) *Route
- func (g *Group) Prefix() string
- func (g *Group) Router() *Router
- func (g *Group) StaticDir(prefixURL, rootDir string) *Route
- func (g *Group) StaticFS(prefixURL string, fs http.FileSystem) *Route
- func (g *Group) StaticFile(path, filePath string) *Route
- func (g *Group) StaticFiles(prefixURL, rootDir, exts string) *Route
- func (g *Group) TRACE(path string, h HandlerFunc, mw ...HandlerFunc) *Route
- func (g *Group) Use(middlewares ...HandlerFunc) *Group
- type HandlerFunc
- type HandlersChain
- type M
- type Param
- type Params
- type Renderer
- type Route
- func (r *Route) Handler() HandlerFunc
- func (r *Route) HandlerName() string
- func (r *Route) Handlers() HandlersChain
- func (r *Route) Info() RouteInfo
- func (r *Route) MethodString(sep string) string
- func (r *Route) Methods() []string
- func (r *Route) Name() string
- func (r *Route) Path() string
- func (r *Route) String() string
- func (r *Route) ToURL(buildArgs ...any) *url.URL
- func (r *Route) Use(middlewares ...HandlerFunc) *Route
- type RouteInfo
- type Router
- func (r *Router) Add(path string, handler HandlerFunc, methods ...string) *Route
- func (r *Router) AddNamed(name, path string, handler HandlerFunc, methods ...string) *Route
- func (r *Router) AddRoute(route *Route) *Route
- func (r *Router) Any(path string, h HandlerFunc, mw ...HandlerFunc) *Route
- func (r *Router) Bind(addr ...string) (net.Listener, error)
- func (r *Router) BuildRequestURL(name string, buildArgs ...any) *url.URL
- func (r *Router) BuildURL(name string, buildArgs ...any) *url.URL
- func (r *Router) CONNECT(path string, h HandlerFunc, mw ...HandlerFunc) *Route
- func (r *Router) Controller(basePath string, c ControllerFace, middles ...HandlerFunc)
- func (r *Router) DELETE(path string, h HandlerFunc, mw ...HandlerFunc) *Route
- func (r *Router) Err() error
- func (r *Router) Freeze()
- func (r *Router) Frozen() bool
- func (r *Router) GET(path string, h HandlerFunc, mw ...HandlerFunc) *Route
- func (r *Router) GetRoute(name string) *Route
- func (r *Router) Group(prefix string, fn func(), middles ...HandlerFunc)
- func (r *Router) HEAD(path string, h HandlerFunc, mw ...HandlerFunc) *Route
- func (r *Router) HandleContext(c *Context)
- func (r *Router) Handlers() HandlersChain
- func (r *Router) IterateRoutes(fn func(*Route))
- func (r *Router) Listen(addr ...string)
- func (r *Router) ListenAddr() string
- func (r *Router) ListenPort() int
- func (r *Router) ListenTLS(addr, certFile, keyFile string)
- func (r *Router) ListenUnix(file string)
- func (r *Router) Listener() net.Listener
- func (r *Router) Match(method, path string) (*Route, []Param, bool)
- func (r *Router) NamedRoutes() map[string]*Route
- func (r *Router) NewGroup(prefix string, middles ...HandlerFunc) *Group
- func (r *Router) NotAllowed(handlers ...HandlerFunc)
- func (r *Router) NotFound(handlers ...HandlerFunc)
- func (r *Router) OPTIONS(path string, h HandlerFunc, mw ...HandlerFunc) *Route
- func (r *Router) PATCH(path string, h HandlerFunc, mw ...HandlerFunc) *Route
- func (r *Router) POST(path string, h HandlerFunc, mw ...HandlerFunc) *Route
- func (r *Router) PUT(path string, h HandlerFunc, mw ...HandlerFunc) *Route
- func (r *Router) Resource(basePath string, controller any, middles ...HandlerFunc)
- func (r *Router) Routes() []RouteInfo
- func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (r *Router) ServeListener(ln net.Listener)
- func (r *Router) StaticDir(prefixURL, rootDir string) *Route
- func (r *Router) StaticFS(prefixURL string, fs http.FileSystem) *Route
- func (r *Router) StaticFile(path, filePath string) *Route
- func (r *Router) StaticFiles(prefixURL, rootDir, exts string) *Route
- func (r *Router) String() string
- func (r *Router) TRACE(path string, h HandlerFunc, mw ...HandlerFunc) *Route
- func (r *Router) Use(handlers ...HandlerFunc)
- func (r *Router) WrapHTTPHandlers(preHandlers ...func(http.Handler) http.Handler) http.Handler
- type Validator
Constants ¶
const ( // ContentType is the standard HTTP Content-Type header key. ContentType = "Content-Type" // ContentBinary is the application/octet-stream content type. ContentBinary = "application/octet-stream" // ContentDisposition is the standard HTTP Content-Disposition header key. ContentDisposition = "Content-Disposition" )
Response header constants used by render helpers.
const ( GET = "GET" HEAD = "HEAD" POST = "POST" PUT = "PUT" PATCH = "PATCH" DELETE = "DELETE" OPTIONS = "OPTIONS" CONNECT = "CONNECT" TRACE = "TRACE" )
HTTP method names. The root rux package re-exports these as constants so external callers reference them as rux.GET, rux.POST, etc.
const ( IndexAction = "Index" CreateAction = "Create" StoreAction = "Store" ShowAction = "Show" EditAction = "Edit" UpdateAction = "Update" DeleteAction = "Delete" )
RESTful action names, mapped to default HTTP methods.
const CTXAllowedMethods = "_allowedMethods"
CTXAllowedMethods is the context key carrying the []string of HTTP methods other than the request's method that would match the same path. The internal 405 handler reads it to build the Allow header.
const CTXRecoverResult = "_recoverResult"
CTXRecoverResult is the context key carrying the recover() return value when OnPanic fires.
const MaxParams = 16
MaxParams is the maximum number of path parameters per route. Inlined storage in Context avoids any heap allocation for params. Registering a route that exceeds this limit panics.
Variables ¶
var RESTFulActions = map[string][]string{ IndexAction: {GET}, CreateAction: {GET}, StoreAction: {POST}, ShowAction: {GET}, EditAction: {GET}, UpdateAction: {PUT, PATCH}, DeleteAction: {DELETE}, }
RESTFulActions maps action method names to their default HTTP verbs.
Functions ¶
func AllMethods ¶
func AllMethods() []string
AllMethods is a synonym for AnyMethods, kept for backward compatibility.
func AnyMethods ¶
func AnyMethods() []string
AnyMethods returns the canonical list of HTTP methods supported by the router. The returned slice is shared — callers must not mutate it.
func Debug ¶
func Debug(val bool)
Debug toggles verbose logging for rux. When enabled, the router prints startup banners and additional diagnostic output.
func HandleFallbackRoute ¶
func HandleFallbackRoute(r *Router)
func HandleMethodNotAllowed ¶
func HandleMethodNotAllowed(r *Router)
func InterceptAll ¶
InterceptAll redirects all requests to the given path.
func MethodsString ¶
func MethodsString() string
MethodsString returns the supported HTTP methods joined by commas.
func StrictLastSlash ¶
func StrictLastSlash(r *Router)
Enable-style aliases, kept so existing rux.New(rux.StrictLastSlash, ...) calls keep working. New code can use the WithXxx forms above.
func UseEncodedPath ¶
func UseEncodedPath(r *Router)
func WithEncodedPath ¶ added in v2.1.0
WithEncodedPath matches against req.URL.EscapedPath() when on.
func WithFallbackRoute ¶ added in v2.1.0
WithFallbackRoute enables the "/*" wildcard route as a global fallback when on.
func WithMethodNotAllowed ¶ added in v2.1.0
WithMethodNotAllowed enables 405 detection across methods when on.
func WithStrictLastSlash ¶ added in v2.1.0
The WithXxx options take the value explicitly, so a setting can also be switched off (useful if a default ever changes) and several can be composed:
r := rux.New(rux.WithMethodNotAllowed(true), rux.WithEncodedPath(false))
Types ¶
type BuildRequestURL ¶
type BuildRequestURL struct {
// contains filtered or unexported fields
}
BuildRequestURL builds a *url.URL from a path template with placeholders.
func NewBuildRequestURL ¶
func NewBuildRequestURL() *BuildRequestURL
NewBuildRequestURL returns an empty builder.
func (*BuildRequestURL) Build ¶
func (b *BuildRequestURL) Build(withParams ...M) *url.URL
Build url. Keys in withParams that look like "{name}" populate path params; any other key becomes a query string parameter.
func (*BuildRequestURL) Host ¶
func (b *BuildRequestURL) Host(host string) *BuildRequestURL
Host set Host
func (*BuildRequestURL) Params ¶
func (b *BuildRequestURL) Params(params M) *BuildRequestURL
Params set Params
func (*BuildRequestURL) Path ¶
func (b *BuildRequestURL) Path(path string) *BuildRequestURL
Path set Path
func (*BuildRequestURL) Queries ¶
func (b *BuildRequestURL) Queries(queries url.Values) *BuildRequestURL
Queries set Queries
func (*BuildRequestURL) Scheme ¶
func (b *BuildRequestURL) Scheme(scheme string) *BuildRequestURL
Scheme set Scheme
func (*BuildRequestURL) User ¶
func (b *BuildRequestURL) User(username, password string) *BuildRequestURL
User set User
type Context ¶
type Context struct {
Req *http.Request
Resp http.ResponseWriter
// Errors accumulated during handling.
Errors []error
// Renderer (optional) used by Context.Render for templated views.
Renderer Renderer
// contains filtered or unexported fields
}
Context carries per-request state through the handler chain. Full version (with renderers, binding, error chain) is built up in Phase 4/5. This skeleton is the minimum for Route/HandlerFunc compilation.
func (*Context) AbortThen ¶
AbortThen marks the context as aborted at the end of the current middleware run while still allowing the caller to chain further response-shaping calls (e.g. c.AbortThen().NoContent()).
func (*Context) AbortWithStatus ¶
AbortWithStatus aborts and writes the given HTTP status. If a message is supplied, it is written via http.Error (which sets the Content-Type to text/plain and writes the body).
func (*Context) Attachment ¶
Attachment serves srcFile as a downloadable attachment named outName.
func (*Context) AutoBind ¶
AutoBind selects a binder based on Content-Type and binds request data.
A multipart/form-data request also fills uploaded file fields, so a struct with a *multipart.FileHeader field is populated by the same call.
Usage:
err := c.AutoBind(&user)
func (*Context) Bind ¶
Bind is an alias for AutoBind — content-type drives binder selection.
Usage:
err := c.Bind(&user)
func (*Context) BindForm ¶
BindForm binds form-encoded request data to obj.
For a multipart/form-data request it binds the uploaded files as well.
func (*Context) ClientIP ¶
ClientIP returns a best-effort client IP, consulting X-Forwarded-For, X-Real-Ip, and finally the connection RemoteAddr.
func (*Context) FastSetCookie ¶
FastSetCookie sets a response cookie with developer-friendly defaults: path=/, httpOnly=true, secure=false. Optional opts run after the cookie is built and let you flip Secure, set SameSite, override Path, etc.
c.FastSetCookie("session", "v", 3600)
c.FastSetCookie("session", "v", 3600, func(ck *http.Cookie) {
ck.Secure = true
ck.SameSite = http.SameSiteStrictMode
})
The defaults are kept for backward compatibility; HTTPS callers should flip Secure via opts (or use SetCookie directly).
func (*Context) FileContent ¶
FileContent serves the given file as text content.
func (*Context) FirstError ¶
FirstError returns the first error recorded via AddError, or nil if none.
func (*Context) HTMLString ¶
HTMLString writes data as text/html.
func (*Context) Init ¶
func (c *Context) Init(w http.ResponseWriter, req *http.Request)
Init prepares c for a new request. Field-only — no slice reallocation.
func (*Context) MatchedPath ¶
MatchedPath returns the route's registered path with placeholders.
func (*Context) MustBind ¶
MustBind binds request data to obj using binder, panicking on error.
Usage:
c.MustBind(&user, binding.JSON)
func (*Context) MustRender ¶
MustRender is Respond's panic-free alias retained for v1 compatibility.
func (*Context) NoContent ¶
func (c *Context) NoContent()
NoContent writes an HTTP 204 response with no body.
func (*Context) Params ¶
Params returns a pointer to the inlined params (avoids 16-Param value copy).
func (*Context) Query ¶
Query returns the URL query value for key. If the key is absent and a default is supplied, the default is returned; otherwise "" is returned.
func (*Context) Render ¶
Render html template via the registered Renderer.
Prefer ShouldRender for callers supplying their own renderer.
func (*Context) ReqCtxValue ¶
ReqCtxValue returns the value associated with key on the request's context.Context, or nil if absent.
func (*Context) SetCookie ¶
func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)
SetCookie sets a response cookie. Path defaults to "/" if empty.
func (*Context) SetHandlers ¶
func (c *Context) SetHandlers(chain HandlersChain)
SetHandlers installs the (already merged) handler chain.
func (*Context) ShouldBind ¶
ShouldBind binds request data to obj using the given binder.
Usage:
err := c.ShouldBind(&user, binding.JSON)
func (*Context) ShouldRender ¶
ShouldRender renders obj with the given renderer and writes status.
func (*Context) StatusCode ¶
StatusCode returns the HTTP status code that will be (or was) written.
func (*Context) Validate ¶
Validate runs the registered binding validator against obj.
The request is passed along, so a validator that implements binding.RequestValidator can inspect it. Recommended: call ShouldBind directly — it binds and validates.
func (*Context) WriteBytes ¶
WriteBytes writes raw bytes to the response, panicking on I/O error.
func (*Context) WriteString ¶
WriteString writes a string to the response.
type ControllerFace ¶
type ControllerFace interface {
AddRoutes(g *Router)
}
ControllerFace is implemented by structs registered via Router.Controller. Each implementation places its route registrations inside AddRoutes; the Router applies the basePath as a group prefix.
type Group ¶ added in v2.1.0
type Group struct {
// contains filtered or unexported fields
}
Group is a route group value: a path prefix plus the middleware every route registered through it inherits.
Router.Group(prefix, fn, middles...) is the closure form; Router.NewGroup returns this value form, which reads closer to gin:
api := r.NewGroup("/api", handlers.BearerAuth())
api.GET("/users", listUsers) // GET /api/users, auth runs first
admin := api.NewGroup("/admin", isAdmin())
admin.DELETE("/users/{id}", deleteUser) // DELETE /api/admin/users/{id}
Middleware order inside a request: global -> group (outer to inner) -> route -> handler.
A Group captures the prefix and middleware of the moment it is created, so it can be stored and used later. Registration must still happen before the router freezes, exactly like Router.GET.
func (*Group) Add ¶ added in v2.1.0
func (g *Group) Add(path string, h HandlerFunc, methods ...string) *Route
Add registers a route on the given methods (defaults to GET when empty).
func (*Group) AddNamed ¶ added in v2.1.0
func (g *Group) AddNamed(name, path string, h HandlerFunc, methods ...string) *Route
AddNamed registers a named route through this group's context.
func (*Group) Any ¶ added in v2.1.0
func (g *Group) Any(path string, h HandlerFunc, mw ...HandlerFunc) *Route
Any registers a route on every supported HTTP method.
func (*Group) CONNECT ¶ added in v2.1.0
func (g *Group) CONNECT(path string, h HandlerFunc, mw ...HandlerFunc) *Route
func (*Group) DELETE ¶ added in v2.1.0
func (g *Group) DELETE(path string, h HandlerFunc, mw ...HandlerFunc) *Route
func (*Group) GET ¶ added in v2.1.0
func (g *Group) GET(path string, h HandlerFunc, mw ...HandlerFunc) *Route
func (*Group) HEAD ¶ added in v2.1.0
func (g *Group) HEAD(path string, h HandlerFunc, mw ...HandlerFunc) *Route
func (*Group) NewGroup ¶ added in v2.1.0
func (g *Group) NewGroup(prefix string, middles ...HandlerFunc) *Group
NewGroup derives a nested group: prefixes concatenate, middleware stacks.
func (*Group) OPTIONS ¶ added in v2.1.0
func (g *Group) OPTIONS(path string, h HandlerFunc, mw ...HandlerFunc) *Route
func (*Group) PATCH ¶ added in v2.1.0
func (g *Group) PATCH(path string, h HandlerFunc, mw ...HandlerFunc) *Route
func (*Group) POST ¶ added in v2.1.0
func (g *Group) POST(path string, h HandlerFunc, mw ...HandlerFunc) *Route
func (*Group) PUT ¶ added in v2.1.0
func (g *Group) PUT(path string, h HandlerFunc, mw ...HandlerFunc) *Route
func (*Group) Prefix ¶ added in v2.1.0
Prefix returns the group's path prefix, including any parent prefix.
func (*Group) StaticDir ¶ added in v2.1.0
StaticDir serves files from rootDir under prefixURL inside the group.
func (*Group) StaticFS ¶ added in v2.1.0
func (g *Group) StaticFS(prefixURL string, fs http.FileSystem) *Route
StaticFS serves files from the given http.FileSystem under prefixURL.
func (*Group) StaticFile ¶ added in v2.1.0
StaticFile serves one file under the group.
func (*Group) StaticFiles ¶ added in v2.1.0
StaticFiles serves files from rootDir under prefixURL. The exts argument is reserved for future extension filtering and is currently ignored.
func (*Group) TRACE ¶ added in v2.1.0
func (g *Group) TRACE(path string, h HandlerFunc, mw ...HandlerFunc) *Route
func (*Group) Use ¶ added in v2.1.0
func (g *Group) Use(middlewares ...HandlerFunc) *Group
Use appends middleware to the group and returns it for chaining. Routes registered afterwards inherit it; routes registered earlier keep the middleware set they were created with.
type HandlerFunc ¶
type HandlerFunc func(c *Context)
HandlerFunc is the standard handler signature.
func HTTPHandler ¶
func HTTPHandler(gh http.Handler) HandlerFunc
HTTPHandler wraps a generic http.Handler as a rux HandlerFunc.
func HTTPHandlerFunc ¶
func HTTPHandlerFunc(hf http.HandlerFunc) HandlerFunc
HTTPHandlerFunc wraps a generic http.HandlerFunc as a rux HandlerFunc.
func WrapH ¶
func WrapH(hh http.Handler) HandlerFunc
WrapH wraps a generic http.Handler as a rux HandlerFunc.
func WrapHF ¶
func WrapHF(hf http.HandlerFunc) HandlerFunc
WrapHF wraps a generic http.HandlerFunc as a rux HandlerFunc.
func WrapHTTPHandler ¶
func WrapHTTPHandler(gh http.Handler) HandlerFunc
WrapHTTPHandler wraps a generic http.Handler as a rux HandlerFunc.
func WrapHTTPHandlerFunc ¶
func WrapHTTPHandlerFunc(hf http.HandlerFunc) HandlerFunc
WrapHTTPHandlerFunc wraps a generic http.HandlerFunc as a rux HandlerFunc.
func (HandlerFunc) ServeHTTP ¶
func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP adapts a HandlerFunc to the http.Handler interface. Used when a single HandlerFunc is mounted into a generic http.Handler stack outside the Router's dispatch path; flushes the deferred status code.
type HandlersChain ¶
type HandlersChain []HandlerFunc
HandlersChain is a list of handlers (middlewares + final handler). The final handler is the last element — there is no separate field.
func (HandlersChain) Last ¶
func (c HandlersChain) Last() HandlerFunc
Last returns the last handler in the chain (i.e. the main handler).
type Params ¶
type Params struct {
// contains filtered or unexported fields
}
Params is a fixed-capacity inline parameter container. It lives directly inside Context, providing zero-allocation parameter passing when the Context itself is reused via sync.Pool.
type Route ¶
Route describes a single registered route.
chain is the user-supplied middlewares followed by the main handler. finalChain is populated by Router.Freeze() and is what dispatch reads.
func (*Route) Handler ¶
func (r *Route) Handler() HandlerFunc
Handler returns the main handler (last element of chain).
func (*Route) HandlerName ¶
HandlerName returns the symbolic name of the main handler.
func (*Route) Handlers ¶
func (r *Route) Handlers() HandlersChain
Handlers returns the user-supplied middlewares (excluding main handler).
func (*Route) MethodString ¶
MethodString joins allowed methods with sep.
func (*Route) ToURL ¶
ToURL builds a request URL for this route using the optional build args. buildArgs may be:
- empty: return the path as-is.
- a single *BuildRequestURL: drive scheme/host/queries from the builder.
- a single M: populate path params and query string.
- alternating k,v pairs: same as a single M built from the pairs.
Path params are expressed using the v1 placeholder form (e.g. "{id}"). originalPath is used so the {name} placeholders are still present even though the registered path has been rewritten to colon syntax.
func (*Route) Use ¶
func (r *Route) Use(middlewares ...HandlerFunc) *Route
Use prepends middleware handlers to this route. Order: middlewares run before the main handler.
type RouteInfo ¶
type RouteInfo struct {
Name string
Path string
HandlerName string
Methods []string
HandlerNum int
}
RouteInfo is a snapshot of a Route's public information.
type Router ¶
type Router struct {
Name string
// Settings.
OnError HandlerFunc
OnPanic HandlerFunc
// contains filtered or unexported fields
}
Router is the central registration and dispatch object.
A Router moves through two lifecycle stages:
- Registration: routes, groups, middlewares are added.
- Frozen: read-only. Routes are dispatched; further registration panics.
The transition is one-way and happens via Freeze (real Freeze logic lands in Phase 4 — this file provides a stub).
func (*Router) Add ¶
func (r *Router) Add(path string, handler HandlerFunc, methods ...string) *Route
Add registers a route on the given methods (defaults to GET if methods empty).
func (*Router) AddNamed ¶
func (r *Router) AddNamed(name, path string, handler HandlerFunc, methods ...string) *Route
AddNamed is like Add with a route name.
func (*Router) Any ¶
func (r *Router) Any(path string, h HandlerFunc, mw ...HandlerFunc) *Route
Any registers a route on every supported HTTP method.
func (*Router) Bind ¶ added in v2.1.0
Bind binds the TCP listener for the resolved address without serving, so callers can read the real address before any traffic arrives. This is what makes an OS-assigned port (":0", "host:0") usable:
ln, err := r.Bind("127.0.0.1:0")
if err != nil {
log.Fatal(err)
}
fmt.Println("listening on", r.ListenAddr()) // 127.0.0.1:50447
r.ServeListener(ln) // blocks
addr follows the same rules as Listen (default "0.0.0.0:8080", honors $PORT).
func (*Router) BuildRequestURL ¶
BuildRequestURL is an alias of BuildURL retained for v1 compatibility.
func (*Router) BuildURL ¶
BuildURL builds a request URL for the named route. buildArgs are forwarded to Route.ToURL; see that method for accepted shapes.
func (*Router) CONNECT ¶
func (r *Router) CONNECT(path string, h HandlerFunc, mw ...HandlerFunc) *Route
func (*Router) Controller ¶
func (r *Router) Controller(basePath string, c ControllerFace, middles ...HandlerFunc)
Controller registers all routes from the controller's AddRoutes method under the given basePath, with shared middlewares.
func (*Router) DELETE ¶
func (r *Router) DELETE(path string, h HandlerFunc, mw ...HandlerFunc) *Route
func (*Router) Err ¶
Err returns the most recent error from Bind / Listen* / ServeListener, or nil when the last serve ended without one.
func (*Router) Freeze ¶
func (r *Router) Freeze()
Freeze marks the router read-only. Subsequent registration calls panic. It merges globalChain into each route's finalChain, builds the 404/405 fallback chains (also globalChain-first) and mirrors GET routes onto HEAD. Idempotent — safe to call multiple times.
func (*Router) GET ¶
func (r *Router) GET(path string, h HandlerFunc, mw ...HandlerFunc) *Route
func (*Router) Group ¶
func (r *Router) Group(prefix string, fn func(), middles ...HandlerFunc)
Group registers all routes added inside fn under the given path prefix. Middlewares supplied as middles run before route-level middlewares. Nested Group calls compose: prefixes concatenate, handlers stack.
func (*Router) HEAD ¶
func (r *Router) HEAD(path string, h HandlerFunc, mw ...HandlerFunc) *Route
func (*Router) HandleContext ¶
HandleContext re-uses an externally constructed Context.
func (*Router) Handlers ¶
func (r *Router) Handlers() HandlersChain
Handlers returns the global middleware chain.
func (*Router) IterateRoutes ¶
IterateRoutes calls fn for each registered route in registration order.
func (*Router) Listen ¶
Listen starts an HTTP server on the resolved address and blocks until the server exits; the error is stored in r.Err.
The listener is bound before serving, so when addr asks for an OS-assigned port the resolved address is the one that gets printed and the one reported by ListenAddr / ListenPort / Listener (from another goroutine, or after Bind).
func (*Router) ListenAddr ¶ added in v2.1.0
ListenAddr returns the resolved "host:port" the router is serving on, e.g. "127.0.0.1:50447" or "[::]:50447" for a wildcard bind, or "" when nothing has been bound.
func (*Router) ListenPort ¶ added in v2.1.0
ListenPort returns the resolved TCP port, or 0 when nothing is bound.
func (*Router) ListenUnix ¶
ListenUnix starts an HTTP server on a Unix domain socket.
func (*Router) Listener ¶ added in v2.1.0
Listener returns the listener the router is serving on, or nil when it is not serving (before Bind/Listen, or after the server exited).
func (*Router) Match ¶
Match looks up route + params for an offline test or debugging. The hot ServeHTTP path does NOT call this — it uses an internal signature that writes params directly into Context with zero allocation.
func (*Router) NamedRoutes ¶
NamedRoutes returns the map of named routes.
func (*Router) NewGroup ¶ added in v2.1.0
func (r *Router) NewGroup(prefix string, middles ...HandlerFunc) *Group
NewGroup returns a Group for prefix. It inherits the enclosing group context (so it can be called inside a closure-style Group) and appends middles after the inherited middleware.
func (*Router) NotAllowed ¶
func (r *Router) NotAllowed(handlers ...HandlerFunc)
NotAllowed sets the handlers chain for HTTP 405 responses. Only consulted when HandleMethodNotAllowed is enabled.
Like NotFound, the global middleware chain runs first and this must be called before the router is frozen.
func (*Router) NotFound ¶
func (r *Router) NotFound(handlers ...HandlerFunc)
NotFound sets the handlers chain for unmatched routes (404).
The global middleware chain runs before these handlers, exactly like it does for matched routes, so auth / security headers / logging cannot be bypassed by requesting an unknown path.
Must be called before the router is frozen (i.e. before the first request), same as Use/GET/...: the composed chain is built in Freeze().
func (*Router) OPTIONS ¶
func (r *Router) OPTIONS(path string, h HandlerFunc, mw ...HandlerFunc) *Route
func (*Router) PATCH ¶
func (r *Router) PATCH(path string, h HandlerFunc, mw ...HandlerFunc) *Route
func (*Router) POST ¶
func (r *Router) POST(path string, h HandlerFunc, mw ...HandlerFunc) *Route
func (*Router) PUT ¶
func (r *Router) PUT(path string, h HandlerFunc, mw ...HandlerFunc) *Route
func (*Router) Resource ¶
func (r *Router) Resource(basePath string, controller any, middles ...HandlerFunc)
Resource registers RESTful routes for the given controller struct.
Methods Path Action Route Name
GET /resource Index resource_index
GET /resource/create Create resource_create
POST /resource Store resource_store
GET /resource/{id} Show resource_show
GET /resource/{id}/edit Edit resource_edit
PUT/PATCH /resource/{id} Update resource_update
DELETE /resource/{id} Delete resource_delete
If the controller has a Uses() map[string][]HandlerFunc method, per-action middlewares are wired automatically.
func (*Router) ServeHTTP ¶
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
ServeHTTP triggers lazy Freeze on first call.
func (*Router) ServeListener ¶ added in v2.1.0
ServeListener serves HTTP on an already-bound listener and blocks until the server exits; the error is stored in r.Err. The listener's address is reflected into ListenAddr / ListenPort.
Use it with Bind, or when the socket is owned by someone else (systemd socket activation, a port pre-bound by a test, a Unix socket). For TLS, call http.ServeTLS(ln, r, certFile, keyFile) directly: Router is an http.Handler.
func (*Router) StaticDir ¶
StaticDir serves files from rootDir under prefixURL using http.FileServer. Inside a closure-style Group the group prefix is included when stripping.
func (*Router) StaticFS ¶
func (r *Router) StaticFS(prefixURL string, fs http.FileSystem) *Route
StaticFS serves files from the given http.FileSystem under prefixURL.
func (*Router) StaticFile ¶
StaticFile registers a single static file under the given path.
func (*Router) StaticFiles ¶
StaticFiles serves files from rootDir under prefixURL. The exts argument is reserved for future extension filtering and is currently ignored.
func (*Router) TRACE ¶
func (r *Router) TRACE(path string, h HandlerFunc, mw ...HandlerFunc) *Route
func (*Router) Use ¶
func (r *Router) Use(handlers ...HandlerFunc)
Use appends global middleware.
It may be called any time before the router freezes (that is, before the first request); after that it panics. Declaring global middleware before your routes is still the clearest style, but the order is not enforced: global middleware is merged into every route chain when the router freezes, so a later Use call also covers routes that were registered earlier.
Note: this means a Use call written inside a Group closure is global, not group-scoped. Pass middleware to Group (or use Group.Use on a Group value) when you want it to apply to that group only.