router

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Overview

Package router builds an http.Handler from typed handlers.

It uses net/http and the pattern syntax of Go 1.22. It adds no third-party router. See the SDD, S4.

A handler returns a Response and never writes to the ResponseWriter, so the transaction middleware commits before anything reaches the client.

Index

Constants

View Source
const (
	// CSRFCookieName is the cookie that carries the signed token.
	CSRFCookieName = "_avero_csrf"
	// CSRFFieldName is the form field that carries the token.
	CSRFFieldName = "_csrf"
	// CSRFHeaderName is the header that carries the token.
	CSRFHeaderName = "X-CSRF-Token"
	// StatusCSRF is the status of a CSRF fault. See the SDD, S10.
	StatusCSRF = 419
)

The names that the CSRF middleware uses.

View Source
const (
	ToastInfo    = "info"
	ToastSuccess = "success"
	ToastWarning = "warning"
	ToastError   = "error"
)

The levels that a Toast carries.

View Source
const FlashCookieName = "_avero_flash"

FlashCookieName is the cookie that carries the toasts across a redirect.

View Source
const HeaderRequestID = "X-Request-Id"

HeaderRequestID names the header that carries the request ID.

View Source
const MinSecretLength = 32

MinSecretLength is the shortest secret that Avero accepts. A short secret makes a signature guessable.

View Source
const ReportSchemaID = "https://avero.dev/schema/routes-report/v1"

ReportSchemaID names the schema that a JSON routes report follows. See router/schema.json.

Variables

View Source
var ReportSchema []byte

ReportSchema holds router/schema.json. `avero routes --json` emits a document that this schema accepts. See AN-3.

Functions

func HasJSONBody

func HasJSONBody(r *http.Request) bool

HasJSONBody reports whether the request carries a JSON body to decode.

func IsEmail

func IsEmail(s string) bool

IsEmail reports whether s is one address. net/mail owns the grammar, so Avero adds no dependency and no pattern of its own.

func IsUUID

func IsUUID(s string) bool

IsUUID reports whether s is a UUID in the 8-4-4-4-12 form.

func NewBindFault

func NewBindFault(parameter, want string) error

NewBindFault builds a bind fault.

func OldFrom

func OldFrom(ctx context.Context) any

OldFrom returns the input that failed validation, as a pointer to the input type. It returns nil when the request passed. S10 fills the form again from it.

func OneOf

func OneOf(s string, values ...string) bool

OneOf reports whether s is one of the values.

func PathValue

func PathValue(r *http.Request, name string) (string, bool)

PathValue returns a path wildcard and reports whether it is present.

func RequestIDFrom

func RequestIDFrom(ctx context.Context) string

RequestIDFrom returns the identifier that RequestID put in ctx. It returns the empty string when the middleware did not run.

func Value

func Value(values url.Values, name string) (string, bool)

Value returns one member of a query string or a form, and reports whether it is present.

Generated code parses the query one time and passes the result here, because url.URL.Query parses the whole string on each call.

func Values

func Values(values url.Values, name string) ([]string, bool)

Values returns every member of a repeated query parameter or form field.

Types

type BindFault

type BindFault struct {
	// Parameter is the name of the path, query, form or body member.
	Parameter string
	// Want states the shape, such as "a whole number".
	Want string
}

BindFault reports a value that does not hold the shape that a field needs. It names the parameter and the shape, and it never carries the value, which can be a secret.

func (*BindFault) Error

func (e *BindFault) Error() string

Error states the fault.

type Binder

type Binder interface {
	Bind(c *Ctx) error
}

Binder fills itself from a request. `avero generate` writes it.

type CookieOption

type CookieOption func(*http.Cookie)

CookieOption configures a cookie that Avero sets.

func CookieDomain

func CookieDomain(domain string) CookieOption

CookieDomain sets the domain of a cookie.

func CookiePath

func CookiePath(path string) CookieOption

CookiePath sets the path of a cookie. The default is the root.

func Secure

func Secure() CookieOption

Secure marks a cookie so that a browser sends it over TLS only. Set it in every environment except local development.

type Ctx

type Ctx struct {
	// contains filtered or unexported fields
}

Ctx carries one request. A handler reads it and returns a Response. A handler never writes to the ResponseWriter, because the transaction commits after the handler returns. See the SDD, S4.

func NewCtx

func NewCtx(w http.ResponseWriter, r *http.Request) *Ctx

NewCtx builds a Ctx for one request. A test calls a handler with it and needs no router. The router builds its own.

func (*Ctx) CSRFToken

func (c *Ctx) CSRFToken() string

CSRFToken returns the token of this request. A form embeds it in a hidden field named _csrf.

func (*Ctx) Context

func (c *Ctx) Context() context.Context

Context returns the request context. It carries the transaction and the session.

func (*Ctx) Error

func (c *Ctx) Error(message string)

Error adds an error message.

func (*Ctx) Header

func (c *Ctx) Header() http.Header

Header returns the response header. A handler sets a header here and the Response writes the body.

func (*Ctx) Info

func (c *Ctx) Info(message string)

Info adds an information message.

func (*Ctx) MustTx

func (c *Ctx) MustTx() *drel.Tx

MustTx returns the transaction and panics when none is present. Use it in a handler that a transaction must always surround, so that a wiring fault fails at once.

func (*Ctx) Partial

func (c *Ctx) Partial() bool

Partial reports whether the client asked for a fragment and not a whole page. htmx and Datastar both mark such a request with a header.

A view uses it to render one fragment. internal/ui therefore needs no import of either library. See the SDD, S12.

func (*Ctx) PathValue

func (c *Ctx) PathValue(name string) string

PathValue returns a value from the pattern, such as {id}.

func (*Ctx) Request

func (c *Ctx) Request() *http.Request

Request returns the request.

func (*Ctx) RequestID

func (c *Ctx) RequestID() string

RequestID returns the identifier of this request.

func (*Ctx) Session

func (c *Ctx) Session() *store.Session

Session returns the auth-all session. It returns nil for an anonymous request.

func (*Ctx) SetContext

func (c *Ctx) SetContext(ctx context.Context)

SetContext replaces the request context. A middleware outside this package calls it to add a value, such as the span that the telemetry middleware starts.

func (*Ctx) Success

func (c *Ctx) Success(message string)

Success adds a success message.

func (*Ctx) Toast

func (c *Ctx) Toast(t Toast)

Toast adds a message to this response.

func (*Ctx) Toasts

func (c *Ctx) Toasts() []Toast

Toasts returns the messages of this response, in the order that the handler added them.

func (*Ctx) Tx

func (c *Ctx) Tx() *drel.Tx

Tx returns the transaction that the transaction middleware opened. It returns nil when no transaction surrounds the request.

The SDD names this method UoW. drel deleted UnitOfWork, because it held no connection and could not write an application row and a control row in one transaction. The context now carries *drel.Tx.

func (*Ctx) User

func (c *Ctx) User() *store.User

User returns the signed-in user. It returns nil for an anonymous request. auth-all attaches the user with RequireAuth or LoadSession.

func (*Ctx) Warning

func (c *Ctx) Warning(message string)

Warning adds a warning message.

func (*Ctx) WriteHeader

func (c *Ctx) WriteHeader(code int)

WriteHeader sends the status one time. A second call does nothing.

func (*Ctx) Writer

func (c *Ctx) Writer() http.ResponseWriter

Writer returns the response writer. A handler must not write to it. The router writes the Response after the transaction commits.

type Fault

type Fault struct {
	// File is the file that registered the route.
	File string `json:"file"`
	// Line is the line that registered the route.
	Line int `json:"line"`
	// Message states the fault.
	Message string `json:"message"`
	// Repair states what to do. It is one sentence.
	Repair string `json:"repair"`
}

Fault is one router fault. It names the position in the code that the person wrote, states what went wrong, and states the repair in one sentence. See DX-6 and DX-7.

runtime.Caller gives a file and a line. It gives no column, so a router fault names a file and a line only.

func (*Fault) Error

func (f *Fault) Error() string

Error returns the position, the message and the repair.

type Faults

type Faults struct {
	Faults []*Fault `json:"faults"`
}

Faults holds every fault that one router found. The router reports every fault, not only the first.

func (*Faults) Error

func (l *Faults) Error() string

Error returns a count and one entry for each fault.

func (*Faults) Unwrap

func (l *Faults) Unwrap() []error

Unwrap returns each fault so that errors.As reaches a single one.

type Fields

type Fields struct {
	// contains filtered or unexported fields
}

Fields collects one message for each field that failed validation. The first message of a field stays, because it names the fault that a person repairs first.

Generated code writes into it. See the SDD, S5.

func FieldsFrom

func FieldsFrom(ctx context.Context) *Fields

FieldsFrom returns the validation result that In put in ctx. It returns nil when the request passed validation. S10 renders the form again from it.

func (*Fields) Add

func (f *Fields) Add(field, message string)

Add records a message for a field. A second message for the same field is dropped.

func (*Fields) Get

func (f *Fields) Get(field string) string

Get returns the message of a field, or the empty string.

func (*Fields) Has

func (f *Fields) Has(field string) bool

Has reports whether the field failed.

func (*Fields) Len

func (f *Fields) Len() int

Len returns the number of fields that failed.

func (*Fields) Map

func (f *Fields) Map() map[string]string

Map returns a copy of the messages, keyed by field name.

func (*Fields) Names

func (f *Fields) Names() []string

Names returns the fields that failed, in the order that they failed.

type Handler

type Handler func(c *Ctx) (Response, error)

Handler is one typed handler. It returns the response and an error.

func In

func In[T any, P interface {
	*T
	Binder
	Validator
}](fn func(c *Ctx, in T) (Response, error),
) Handler

In adapts a typed handler to the router.

The constraint requires the Bind and Validate methods that `avero generate` writes, so a missing or stale generated file is a compile fault at the route and never a fault at request time. See AN-2.

r.Post("/things", avero.In(m.Create))

type Middleware

type Middleware struct {
	// Name identifies the middleware in the routes output.
	Name string
	// Wrap returns a handler that calls next.
	Wrap func(next Handler) Handler
}

Middleware wraps a handler. It carries a name, because `avero routes` prints the chain of each route. See the SDD, S4.

func AccessLog

func AccessLog(log *slog.Logger) Middleware

AccessLog writes one line for each request. It records the method, the path, the status, the duration and the request ID.

S3 adds the trace ID to the same line.

func Adapt

func Adapt(name string, mw func(http.Handler) http.Handler) Middleware

Adapt turns a net/http middleware into an Avero middleware, so that a library such as auth-all composes with a typed handler.

The adapted middleware sees a handler that runs the rest of the chain and writes nothing. When it calls that handler, Adapt returns the Response that the chain produced. When it answers the request itself, for example a 401 from RequireAuth, Adapt returns a response that writes nothing more, because the middleware already wrote the whole answer.

func CSRF

func CSRF(secret config.Secret, opts ...CookieOption) Middleware

CSRF protects an unsafe method with a signed double-submit token.

A safe method receives a token in a signed cookie. An unsafe method must send the same token back in the form field _csrf or in the X-CSRF-Token header. A request that does not match returns 419 and never reaches the handler.

The token needs no server state, so it works for an anonymous visitor and for a signed-in one. auth-all owns the authentication session.

func Flash

func Flash(secret config.Secret, opts ...CookieOption) Middleware

Flash carries a Toast from one request to the next.

It reads the toasts of the previous request into the context and clears the cookie. After the handler returns, it writes the toasts into the cookie only when the response is a redirect. Any other response shows the toasts itself, so it needs no cookie.

func Recover

func Recover(log *slog.Logger) Middleware

Recover turns a panic into 500. It logs the value and the stack, and it never writes either to the client.

Recover sits outside the transaction middleware in the scaffolded order, so the transaction rolls back before Recover answers. See the SDD, S4.

func RequestID

func RequestID() Middleware

RequestID gives each request an identifier. It keeps the identifier that the client sent, so that a trace crosses a service boundary. It writes the identifier to the response header.

S3 puts the same identifier on every log line inside the request.

func Transaction

func Transaction(e *drel.Engine) Middleware

Transaction opens a drel transaction, puts it in the request context, and decides the commit from the response.

It commits on a 2xx or a 3xx response. It rolls back on every other status, on a handler error and on a panic. See the SDD, S4.

The handler returns a Response and writes nothing, so the commit happens before any byte reaches the client. A commit that fails therefore never follows a sent 200.

type Option

type Option func(*Router)

Option configures a router.

func WithErrorResponse

func WithErrorResponse(fn func(c *Ctx, err error) Response) Option

WithErrorResponse sets the response that a handler error produces. The default answers 500 and never prints the message of the error.

func WithValidationResponse

func WithValidationResponse(fn func(c *Ctx, f *Fields) Response) Option

WithValidationResponse sets the response that a validation fault produces. The default answers 422 with a map of field name to message. The SSR shape replaces it, so the middleware renders the form again with the errors and the old input. See the SDD, S5.

type Report

type Report struct {
	// Routes holds one row for each route, ordered by pattern and then by
	// method, so that two runs give the same order. See AN-4.
	Routes []Route `json:"routes"`
}

Report lists every route of a router. `avero routes` prints it.

func (*Report) MarshalJSON

func (rep *Report) MarshalJSON() ([]byte, error)

MarshalJSON emits the report with a stable schema. See AN-3.

func (*Report) Route

func (rep *Report) Route(method, pattern string) (Route, bool)

Route returns the row with this method and pattern.

func (*Report) String

func (rep *Report) String() string

String returns a table with a header row and one row for each route.

type Response

type Response interface {
	// Status is the HTTP status code that Write will send.
	Status() int
	// Write sends the response. The router calls it one time.
	Write(c *Ctx) error
}

Response is the result of a handler. It states its status before it writes, so the transaction middleware decides the commit before anything reaches the client. See the SDD, S4.

A handler never writes to the ResponseWriter. It returns a Response and the router writes it after the transaction commits.

func Empty

func Empty(code int) Response

Empty returns a status with no body.

func HTML

func HTML(code int, body string) Response

HTML returns an HTML response. S10 renders a templ component with View.

func JSON

func JSON(code int, body any) Response

JSON returns a response that encodes body as JSON.

func NoContent

func NoContent() Response

NoContent returns 204 with no body.

func Redirect

func Redirect(code int, to string) Response

Redirect returns a redirect. Use 303 after a form post and 302 otherwise.

func Status

func Status(code int) Response

Status returns a response that carries the standard text of the code.

func Text

func Text(code int, body string) Response

Text returns a plain text response.

type Route

type Route struct {
	// Method is the HTTP method, or * for a mounted handler.
	Method string `json:"method"`
	// Pattern is the full pattern, with every group prefix joined.
	Pattern string `json:"pattern"`
	// Handler is the name of the function that serves the route.
	Handler string `json:"handler"`
	// Middleware names the chain, from the outermost to the innermost.
	Middleware []string `json:"middleware"`
	// File is the file that registered the route.
	File string `json:"file"`
	// Line is the line that registered the route.
	Line int `json:"line"`
	// Mounted reports an http.Handler that Mount serves. No transaction
	// surrounds a mounted handler.
	Mounted bool `json:"mounted"`
	// contains filtered or unexported fields
}

Route is one registered route. `avero routes` prints it. See AN-3.

type Router

type Router struct {
	// contains filtered or unexported fields
}

Router registers routes and builds the http.Handler that serves them.

A Router value is one scope. Group returns a child scope that carries a prefix and its own middleware. A child never changes its parent.

func New

func New(opts ...Option) *Router

New builds a router.

func (*Router) Delete

func (r *Router) Delete(pattern string, h Handler)

Delete registers a DELETE route.

func (*Router) Faults

func (r *Router) Faults() []*Fault

Faults returns every registration fault that this router holds, in the order that the router found them. The module system reads it to name the module that holds a fault. See the SDD, S6.

func (*Router) Get

func (r *Router) Get(pattern string, h Handler)

Get registers a GET route.

func (*Router) Group

func (r *Router) Group(prefix string, fn func(g *Router))

Group returns a child scope with a prefix. The middleware that the child adds applies inside the group only.

r.Group("/api", func(g *router.Router) {
    g.Use(router.RequireJSON())
    g.Get("/things", listThings)
})

func (*Router) Handle

func (r *Router) Handle(method, pattern string, h Handler)

Handle registers a route for any method.

func (*Router) Handler

func (r *Router) Handler() (http.Handler, error)

Handler builds the http.Handler. It returns every registration fault and no handler, so a fault stops the process before it serves. See DX-8.

func (*Router) Merge

func (r *Router) Merge(src *Router)

Merge copies every route and every fault of src into this scope.

The prefix of this scope joins the pattern of each route. The middleware of this scope wraps the middleware that src holds. A duplicate pattern becomes a fault, in the same form as a direct registration.

The module system builds one router for each module and merges it. A module therefore registers its routes one time. See the SDD, S6.

func (*Router) Mount

func (r *Router) Mount(prefix string, h http.Handler)

Mount serves an http.Handler under a prefix. The handler sees the path with the prefix removed.

A mounted handler writes to the ResponseWriter itself, so no transaction surrounds it. `avero routes` marks it.

func (*Router) Patch

func (r *Router) Patch(pattern string, h Handler)

Patch registers a PATCH route.

func (*Router) Post

func (r *Router) Post(pattern string, h Handler)

Post registers a POST route.

func (*Router) Put

func (r *Router) Put(pattern string, h Handler)

Put registers a PUT route.

func (*Router) Report

func (r *Router) Report() (*Report, error)

Report returns the routes of the router. It returns every registration fault and no report, so a fault stops the process before it serves.

func (*Router) Routes

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

Routes returns every route that this router holds, in registration order. It reports no fault. Call Report for the sorted table and the faults.

The module system reads it to name the routes of one module. See the SDD, S6.

func (*Router) Use

func (r *Router) Use(mws ...Middleware)

Use adds middleware to this scope. It applies to every route that this scope registers after the call, and to every child group.

type Toast

type Toast struct {
	// Level is one of info, success, warning or error.
	Level string `json:"level"`
	// Message is the text that the person reads.
	Message string `json:"message"`
}

Toast is one message that the next rendered page shows. The flash middleware carries a toast across a redirect. See the SDD, S10.

type Validator

type Validator interface {
	Validate(c *Ctx, f *Fields)
}

Validator checks itself and records a message for each field that failed. `avero generate` writes it.

Jump to

Keyboard shortcuts

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