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
- Variables
- func HasJSONBody(r *http.Request) bool
- func IsEmail(s string) bool
- func IsUUID(s string) bool
- func NewBindFault(parameter, want string) error
- func OldFrom(ctx context.Context) any
- func OneOf(s string, values ...string) bool
- func PathValue(r *http.Request, name string) (string, bool)
- func RequestIDFrom(ctx context.Context) string
- func Value(values url.Values, name string) (string, bool)
- func Values(values url.Values, name string) ([]string, bool)
- type BindFault
- type Binder
- type CookieOption
- type Ctx
- func (c *Ctx) CSRFToken() string
- func (c *Ctx) Context() context.Context
- func (c *Ctx) Error(message string)
- func (c *Ctx) Header() http.Header
- func (c *Ctx) Info(message string)
- func (c *Ctx) MustTx() *drel.Tx
- func (c *Ctx) Partial() bool
- func (c *Ctx) PathValue(name string) string
- func (c *Ctx) Request() *http.Request
- func (c *Ctx) RequestID() string
- func (c *Ctx) Session() *store.Session
- func (c *Ctx) SetContext(ctx context.Context)
- func (c *Ctx) Success(message string)
- func (c *Ctx) Toast(t Toast)
- func (c *Ctx) Toasts() []Toast
- func (c *Ctx) Tx() *drel.Tx
- func (c *Ctx) User() *store.User
- func (c *Ctx) Warning(message string)
- func (c *Ctx) WriteHeader(code int)
- func (c *Ctx) Writer() http.ResponseWriter
- type Fault
- type Faults
- type Fields
- type Handler
- type Middleware
- func AccessLog(log *slog.Logger) Middleware
- func Adapt(name string, mw func(http.Handler) http.Handler) Middleware
- func CSRF(secret config.Secret, opts ...CookieOption) Middleware
- func Flash(secret config.Secret, opts ...CookieOption) Middleware
- func Recover(log *slog.Logger) Middleware
- func RequestID() Middleware
- func Transaction(e *drel.Engine) Middleware
- type Option
- type Report
- type Response
- type Route
- type Router
- func (r *Router) Delete(pattern string, h Handler)
- func (r *Router) Faults() []*Fault
- func (r *Router) Get(pattern string, h Handler)
- func (r *Router) Group(prefix string, fn func(g *Router))
- func (r *Router) Handle(method, pattern string, h Handler)
- func (r *Router) Handler() (http.Handler, error)
- func (r *Router) Merge(src *Router)
- func (r *Router) Mount(prefix string, h http.Handler)
- func (r *Router) Patch(pattern string, h Handler)
- func (r *Router) Post(pattern string, h Handler)
- func (r *Router) Put(pattern string, h Handler)
- func (r *Router) Report() (*Report, error)
- func (r *Router) Routes() []Route
- func (r *Router) Use(mws ...Middleware)
- type Toast
- type Validator
Constants ¶
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.
const ( ToastInfo = "info" ToastSuccess = "success" ToastWarning = "warning" ToastError = "error" )
The levels that a Toast carries.
const FlashCookieName = "_avero_flash"
FlashCookieName is the cookie that carries the toasts across a redirect.
const HeaderRequestID = "X-Request-Id"
HeaderRequestID names the header that carries the request ID.
const MinSecretLength = 32
MinSecretLength is the shortest secret that Avero accepts. A short secret makes a signature guessable.
const ReportSchemaID = "https://avero.dev/schema/routes-report/v1"
ReportSchemaID names the schema that a JSON routes report follows. See router/schema.json.
Variables ¶
var ReportSchema []byte
ReportSchema holds router/schema.json. `avero routes --json` emits a document that this schema accepts. See AN-3.
Functions ¶
func HasJSONBody ¶
HasJSONBody reports whether the request carries a JSON body to decode.
func IsEmail ¶
IsEmail reports whether s is one address. net/mail owns the grammar, so Avero adds no dependency and no pattern of its own.
func NewBindFault ¶
NewBindFault builds a bind fault.
func OldFrom ¶
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 RequestIDFrom ¶
RequestIDFrom returns the identifier that RequestID put in ctx. It returns the empty string when the middleware did not run.
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.
type CookieOption ¶
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 ¶
CSRFToken returns the token of this request. A form embeds it in a hidden field named _csrf.
func (*Ctx) Context ¶
Context returns the request context. It carries the transaction and the session.
func (*Ctx) Header ¶
Header returns the response header. A handler sets a header here and the Response writes the body.
func (*Ctx) MustTx ¶
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 ¶
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) Session ¶
Session returns the auth-all session. It returns nil for an anonymous request.
func (*Ctx) SetContext ¶
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) Toasts ¶
Toasts returns the messages of this response, in the order that the handler added them.
func (*Ctx) 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 ¶
User returns the signed-in user. It returns nil for an anonymous request. auth-all attaches the user with RequireAuth or LoadSession.
func (*Ctx) WriteHeader ¶
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.
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.
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 ¶
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 ¶
Add records a message for a field. A second message for the same field is dropped.
type Handler ¶
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 ¶
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 ¶
WithErrorResponse sets the response that a handler error produces. The default answers 500 and never prints the message of the error.
func WithValidationResponse ¶
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 ¶
MarshalJSON emits the report with a stable schema. See AN-3.
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.
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 (*Router) Faults ¶
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) Group ¶
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) Handler ¶
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 ¶
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 ¶
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) Report ¶
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 ¶
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.