core

package
v2.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 8, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
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.

View Source
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.

View Source
const (
	IndexAction  = "Index"
	CreateAction = "Create"
	StoreAction  = "Store"
	ShowAction   = "Show"
	EditAction   = "Edit"
	UpdateAction = "Update"
	DeleteAction = "Delete"
)

RESTful action names, mapped to default HTTP methods.

View Source
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.

View Source
const CTXRecoverResult = "_recoverResult"

CTXRecoverResult is the context key carrying the recover() return value when OnPanic fires.

View Source
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

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

func InterceptAll(path string) func(*Router)

InterceptAll redirects all requests to the given path.

func IsDebug

func IsDebug() bool

IsDebug reports whether debug mode is active.

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

func WithEncodedPath(on bool) func(*Router)

WithEncodedPath matches against req.URL.EscapedPath() when on.

func WithFallbackRoute added in v2.1.0

func WithFallbackRoute(on bool) func(*Router)

WithFallbackRoute enables the "/*" wildcard route as a global fallback when on.

func WithMethodNotAllowed added in v2.1.0

func WithMethodNotAllowed(on bool) func(*Router)

WithMethodNotAllowed enables 405 detection across methods when on.

func WithStrictLastSlash added in v2.1.0

func WithStrictLastSlash(on bool) func(*Router)

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) Abort

func (c *Context) Abort()

Abort prevents subsequent handlers from running.

func (*Context) AbortThen

func (c *Context) AbortThen() *Context

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

func (c *Context) AbortWithStatus(status int, msg ...string)

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) AddError

func (c *Context) AddError(err error)

AddError records an error to be processed by Router.OnError.

func (*Context) Attachment

func (c *Context) Attachment(srcFile, outName string)

Attachment serves srcFile as a downloadable attachment named outName.

func (*Context) AutoBind

func (c *Context) AutoBind(obj any) error

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) Back

func (c *Context) Back(optionalCode ...int)

Back redirects to the request's Referer header (302 by default).

func (*Context) Binary

func (c *Context) Binary(status int, in io.ReadSeeker, outName string, inline bool)

Binary writes the contents of in as a binary attachment (or inline).

func (*Context) Bind

func (c *Context) Bind(obj any) error

Bind is an alias for AutoBind — content-type drives binder selection.

Usage:

err := c.Bind(&user)

func (*Context) BindForm

func (c *Context) BindForm(obj any) error

BindForm binds form-encoded request data to obj.

For a multipart/form-data request it binds the uploaded files as well.

func (*Context) BindJSON

func (c *Context) BindJSON(obj any) error

BindJSON binds the JSON request body to obj.

func (*Context) BindXML

func (c *Context) BindXML(obj any) error

BindXML binds the XML request body to obj.

func (*Context) Blob

func (c *Context) Blob(status int, contentType string, data []byte)

Blob writes raw bytes with the given contentType.

func (*Context) ClientIP

func (c *Context) ClientIP() string

ClientIP returns a best-effort client IP, consulting X-Forwarded-For, X-Real-Ip, and finally the connection RemoteAddr.

func (*Context) Cookie

func (c *Context) Cookie(name string) string

Cookie reads a request cookie value, or "" if not set.

func (*Context) DelCookie

func (c *Context) DelCookie(names ...string)

DelCookie deletes one or more cookies by setting MaxAge=-1.

func (*Context) Err

func (c *Context) Err() error

Err returns the most recent error or nil.

func (*Context) FastSetCookie

func (c *Context) FastSetCookie(name, value string, maxAge int, opts ...func(*http.Cookie))

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) File

func (c *Context) File(filePath string)

File serves a single file via http.ServeFile.

func (*Context) FileContent

func (c *Context) FileContent(file string, names ...string)

FileContent serves the given file as text content.

func (*Context) FirstError

func (c *Context) FirstError() error

FirstError returns the first error recorded via AddError, or nil if none.

func (*Context) Get

func (c *Context) Get(key string) (any, bool)

Get retrieves user data set by Set.

func (*Context) HTML

func (c *Context) HTML(status int, data []byte)

HTML writes data as text/html. Empty data still flushes the headers.

func (*Context) HTMLString

func (c *Context) HTMLString(status int, data string)

HTMLString writes data as text/html.

func (*Context) HTTPError

func (c *Context) HTTPError(msg string, status int)

HTTPError writes a plain-text error response.

func (*Context) Header

func (c *Context) Header(key string) string

Header returns the first request header value for key, or "" if absent.

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) Inline

func (c *Context) Inline(srcFile, outName string)

Inline serves srcFile inline (rendered in browser) with name outName.

func (*Context) IsAborted

func (c *Context) IsAborted() bool

IsAborted reports whether Abort was called.

func (*Context) JSON

func (c *Context) JSON(status int, obj any)

JSON writes obj as a JSON response.

func (*Context) JSONBytes

func (c *Context) JSONBytes(status int, bs []byte)

JSONBytes writes pre-encoded JSON bytes.

func (*Context) JSONP

func (c *Context) JSONP(status int, callback string, obj any)

JSONP writes obj as a JSONP response with the given callback name.

func (*Context) Length

func (c *Context) Length() int

Length returns the number of body bytes written so far.

func (*Context) MatchedPath

func (c *Context) MatchedPath() string

MatchedPath returns the route's registered path with placeholders.

func (*Context) MustBind

func (c *Context) MustBind(obj any, binder binding.Binder)

MustBind binds request data to obj using binder, panicking on error.

Usage:

c.MustBind(&user, binding.JSON)

func (*Context) MustRender

func (c *Context) MustRender(status int, obj any, renderer render.Renderer)

MustRender is Respond's panic-free alias retained for v1 compatibility.

func (*Context) Next

func (c *Context) Next()

Next advances to the next handler in the chain.

func (*Context) NoContent

func (c *Context) NoContent()

NoContent writes an HTTP 204 response with no body.

func (*Context) Param

func (c *Context) Param(name string) string

Param returns the value of the named path parameter, or "" if absent.

func (*Context) Params

func (c *Context) Params() *Params

Params returns a pointer to the inlined params (avoids 16-Param value copy).

func (*Context) Query

func (c *Context) Query(key string, defVal ...string) string

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) Redirect

func (c *Context) Redirect(path string, optionalCode ...int)

Redirect issues an HTTP redirect. Default code is 302 Found.

func (*Context) Render

func (c *Context) Render(status int, name string, data any) (err error)

Render html template via the registered Renderer.

Prefer ShouldRender for callers supplying their own renderer.

func (*Context) ReqCtxValue

func (c *Context) ReqCtxValue(key any) any

ReqCtxValue returns the value associated with key on the request's context.Context, or nil if absent.

func (*Context) Respond

func (c *Context) Respond(status int, obj any, renderer render.Renderer)

Respond renders obj and records render errors on the Context.

func (*Context) Route

func (c *Context) Route() *Route

Route returns the matched Route or nil.

func (*Context) Router

func (c *Context) Router() *Router

Router returns the Router that dispatched this request.

func (*Context) SafeGet

func (c *Context) SafeGet(key string) any

SafeGet returns the value or panics — for required keys.

func (*Context) Set

func (c *Context) Set(key string, value any)

Set stores arbitrary user data. Allocates the map on first call.

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) SetHeader

func (c *Context) SetHeader(key, value string)

SetHeader sets a response header value.

func (*Context) SetStatus

func (c *Context) SetStatus(status int)

SetStatus writes the HTTP status code to the response.

func (*Context) ShouldBind

func (c *Context) ShouldBind(obj any, binder binding.Binder) error

ShouldBind binds request data to obj using the given binder.

Usage:

err := c.ShouldBind(&user, binding.JSON)

func (*Context) ShouldRender

func (c *Context) ShouldRender(status int, obj any, renderer render.Renderer) error

ShouldRender renders obj with the given renderer and writes status.

func (*Context) StatusCode

func (c *Context) StatusCode() int

StatusCode returns the HTTP status code that will be (or was) written.

func (*Context) Stream

func (c *Context) Stream(status int, contentType string, r io.Reader)

Stream copies an io.Reader to the response.

func (*Context) Text

func (c *Context) Text(status int, str string)

Text writes str as plain text.

func (*Context) URL

func (c *Context) URL() *url.URL

URL is a shortcut for c.Req.URL.

func (*Context) Validate

func (c *Context) Validate(obj any) error

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

func (c *Context) WriteBytes(bt []byte)

WriteBytes writes raw bytes to the response, panicking on I/O error.

func (*Context) WriteString

func (c *Context) WriteString(str string)

WriteString writes a string to the response.

func (*Context) XML

func (c *Context) XML(status int, obj any, indents ...string)

XML writes obj as an XML response. The first indent arg, if any, is applied.

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

func (g *Group) Prefix() string

Prefix returns the group's path prefix, including any parent prefix.

func (*Group) Router added in v2.1.0

func (g *Group) Router() *Router

Router returns the router this group registers routes on.

func (*Group) StaticDir added in v2.1.0

func (g *Group) StaticDir(prefixURL, rootDir string) *Route

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

func (g *Group) StaticFile(path, filePath string) *Route

StaticFile serves one file under the group.

func (*Group) StaticFiles added in v2.1.0

func (g *Group) StaticFiles(prefixURL, rootDir, exts string) *Route

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 M

type M map[string]any

M is a generic map type used for params, payloads, and URL builders.

type Param

type Param struct {
	Key   string
	Value string
}

Param is a single path parameter.

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.

func (*Params) Get

func (p *Params) Get(name string) string

Get returns the value for name, or "" if not found.

func (*Params) Has

func (p *Params) Has(name string) bool

Has reports whether a parameter with the given name exists.

func (*Params) Int

func (p *Params) Int(name string) int

Int parses the named parameter as int, returning 0 on miss or parse error.

func (*Params) Len

func (p *Params) Len() int

Len returns the number of parameters.

func (*Params) Reset

func (p *Params) Reset()

Reset clears the params (called by Context.Reset on pool return).

func (*Params) Snapshot

func (p *Params) Snapshot() []Param

Snapshot returns a heap-allocated copy of the params slice. Use this when you need to retain params beyond the handler scope (e.g., goroutines, async logging).

type Renderer

type Renderer interface {
	Render(io.Writer, string, any, *Context) error
}

Renderer interface for template rendering.

type Route

type Route struct {
	Opts map[string]any
	// contains filtered or unexported fields
}

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

func (r *Route) HandlerName() string

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) Info

func (r *Route) Info() RouteInfo

Info returns a RouteInfo snapshot.

func (*Route) MethodString

func (r *Route) MethodString(sep string) string

MethodString joins allowed methods with sep.

func (*Route) Methods

func (r *Route) Methods() []string

Methods returns the route's allowed methods.

func (*Route) Name

func (r *Route) Name() string

Name returns the route's name.

func (*Route) Path

func (r *Route) Path() string

Path returns the route's path.

func (*Route) String

func (r *Route) String() string

String returns a debug representation of the route.

func (*Route) ToURL

func (r *Route) ToURL(buildArgs ...any) *url.URL

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 New

func New(opts ...func(*Router)) *Router

New constructs a Router with optional configuration.

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) AddRoute

func (r *Router) AddRoute(route *Route) *Route

AddRoute registers a pre-constructed Route.

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

func (r *Router) Bind(addr ...string) (net.Listener, error)

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

func (r *Router) BuildRequestURL(name string, buildArgs ...any) *url.URL

BuildRequestURL is an alias of BuildURL retained for v1 compatibility.

func (*Router) BuildURL

func (r *Router) BuildURL(name string, buildArgs ...any) *url.URL

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

func (r *Router) Err() error

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) Frozen

func (r *Router) Frozen() bool

Frozen reports whether the router is in frozen (read-only) state.

func (*Router) GET

func (r *Router) GET(path string, h HandlerFunc, mw ...HandlerFunc) *Route

func (*Router) GetRoute

func (r *Router) GetRoute(name string) *Route

GetRoute returns a named route or nil.

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

func (r *Router) HandleContext(c *Context)

HandleContext re-uses an externally constructed Context.

func (*Router) Handlers

func (r *Router) Handlers() HandlersChain

Handlers returns the global middleware chain.

func (*Router) IterateRoutes

func (r *Router) IterateRoutes(fn func(*Route))

IterateRoutes calls fn for each registered route in registration order.

func (*Router) Listen

func (r *Router) Listen(addr ...string)

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

func (r *Router) ListenAddr() string

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

func (r *Router) ListenPort() int

ListenPort returns the resolved TCP port, or 0 when nothing is bound.

func (*Router) ListenTLS

func (r *Router) ListenTLS(addr, certFile, keyFile string)

ListenTLS starts an HTTPS server on the resolved address (see Listen).

func (*Router) ListenUnix

func (r *Router) ListenUnix(file string)

ListenUnix starts an HTTP server on a Unix domain socket.

func (*Router) Listener added in v2.1.0

func (r *Router) Listener() net.Listener

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

func (r *Router) Match(method, path string) (*Route, []Param, bool)

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

func (r *Router) NamedRoutes() map[string]*Route

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) Routes

func (r *Router) Routes() []RouteInfo

Routes returns all routes as RouteInfo snapshots in registration order.

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

func (r *Router) ServeListener(ln net.Listener)

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

func (r *Router) StaticDir(prefixURL, rootDir string) *Route

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

func (r *Router) StaticFile(path, filePath string) *Route

StaticFile registers a single static file under the given path.

func (*Router) StaticFiles

func (r *Router) StaticFiles(prefixURL, rootDir, exts string) *Route

StaticFiles serves files from rootDir under prefixURL. The exts argument is reserved for future extension filtering and is currently ignored.

func (*Router) String

func (r *Router) String() string

String returns a human-readable snapshot of registered routes.

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.

func (*Router) WrapHTTPHandlers

func (r *Router) WrapHTTPHandlers(preHandlers ...func(http.Handler) http.Handler) http.Handler

WrapHTTPHandlers wraps the router in zero or more net/http middlewares. The leftmost wrapper runs first.

type Validator

type Validator interface {
	Validate(i any) error
}

Validator interface for struct validation.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL