router

package
v0.3.0 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 ProblemContentType = "application/problem+json"

ProblemContentType is the media type of a problem document. RFC 9457 states it.

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 (
	// ErrNotFound states that the path names no thing. 404.
	ErrNotFound = NewProblem(http.StatusNotFound, "")
	// ErrUnauthorized states that the request carries no identity. 401.
	ErrUnauthorized = NewProblem(http.StatusUnauthorized, "")
	// ErrForbidden states that the identity may not do this. 403.
	ErrForbidden = NewProblem(http.StatusForbidden, "")
	// ErrConflict states that the state of the thing refuses the change. 409.
	ErrConflict = NewProblem(http.StatusConflict, "")
	// ErrBadRequest states that the request does not read. 400.
	ErrBadRequest = NewProblem(http.StatusBadRequest, "")
	// ErrInternal states a fault of the service. 500.
	ErrInternal = NewProblem(http.StatusInternalServerError, "")
)

The problems that a service answers most. Each one states the status and the title, and the caller adds the detail that names the case.

Compare with errors.Is, because each helper returns a new value:

if errors.Is(err, avero.ErrNotFound) { ... }
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 Delete added in v0.3.0

func Delete[T any, P Input[T], V any](r *Router, pattern string,
	fn func(c *Ctx, in T) (V, error), opts ...OpOption,
)

Delete registers a typed DELETE route.

func Get added in v0.3.0

func Get[T any, P Input[T], V any](r *Router, pattern string,
	fn func(c *Ctx, in T) (V, error), opts ...OpOption,
)

Get registers a typed GET route.

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 Patch added in v0.3.0

func Patch[T any, P Input[T], V any](r *Router, pattern string,
	fn func(c *Ctx, in T) (V, error), opts ...OpOption,
)

Patch registers a typed PATCH route.

func PathValue

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

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

func Post added in v0.3.0

func Post[T any, P Input[T], V any](r *Router, pattern string,
	fn func(c *Ctx, in T) (V, error), opts ...OpOption,
)

Post registers a typed POST route. The success answer is 201.

func Put added in v0.3.0

func Put[T any, P Input[T], V any](r *Router, pattern string,
	fn func(c *Ctx, in T) (V, error), opts ...OpOption,
)

Put registers a typed PUT route.

func Register added in v0.3.0

func Register[T any, P Input[T], V any](
	r *Router, method, pattern string,
	fn func(c *Ctx, in T) (V, error),
	opts ...OpOption,
)

Register adds one typed route.

A handler returns the thing that it answers, as an ordinary Go function does. The type of the input and the type of the answer come from its signature, so a change of either is a compile fault. No wrapper surrounds the handler, and no comment states the answer.

avero.Get(r, "/posts/{id}", m.Show)

func (m *Module) Show(c *avero.Ctx, in ShowInput) (View, error)

The method of the route states the status: a POST answers 201 and every other method answers 200. A handler that answers no body returns avero.NoBody, and the status is 204. Ctx.Status names another status.

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 API added in v0.3.0

type API struct {
	// Title is the name of the API. An empty value reads the name of the
	// module of the binary.
	Title string
	// Version is the version of the description. An empty value reads the
	// version of the binary.
	Version string
	// Description states what the API does. A reader of the document reads
	// it first.
	Description string
	// TermsOfService is the address of the terms.
	TermsOfService string
	// Contact names the people who own the API.
	Contact *Contact
	// License names the licence of the API.
	License *License
	// Servers name the addresses that answer.
	Servers []Server
	// Security holds the schemes of the identity, by name.
	Security map[string]SecurityScheme
	// Require names the schemes that every route needs. A route states
	// Public to stand outside them.
	Require []string
	// Tags describe the groups that the operations name.
	Tags []Tag
	// ExternalDocs names a document that stands outside this one.
	ExternalDocs *ExternalDocs
}

API states the facts of the whole description of an API.

A route states its own operation. This states what stands above every route: the name, the prose, the addresses, the schemes of the identity and the groups.

r := avero.NewRouter(avero.WithAPI(avero.API{
    Title:       "Blog",
    Description: "The service that holds the posts.",
    Servers: []Server{{URL: "https://api.example.com", Description: "production"}},
    Security: map[string]SecurityScheme{
        "bearer": avero.BearerAuth("The token of a session."),
    },
    Require: []string{"bearer"},
}))

type Answer added in v0.3.0

type Answer struct {
	// Code is the HTTP status.
	Code int `json:"code"`
	// Description states the case that produces this answer.
	Description string `json:"description,omitempty"`
	// Headers name the headers that this answer carries.
	Headers []Header `json:"headers,omitempty"`
	// contains filtered or unexported fields
}

Answer is one status that an operation writes, and the type of its body.

Two answers of one status state that the answer carries one of two shapes, which OpenAPI writes as oneOf.

func (Answer) Body added in v0.3.0

func (a Answer) Body() reflect.Type

Body returns the type of the body of the answer, or nil.

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 Contact added in v0.3.0

type Contact struct {
	Name  string `json:"name,omitempty"`
	URL   string `json:"url,omitempty"`
	Email string `json:"email,omitempty"`
}

Contact names the people who own the API.

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) Status added in v0.3.0

func (c *Ctx) Status(code int)

Status names the status of this one answer.

A handler that returns a value needs it for the case that the method does not state. A GET answers 200 and a POST answers 201, so a handler calls this for 202 or for 200 after a POST.

func (m *Module) Create(c *avero.Ctx, in CreateInput) (View, error) {
    c.Status(http.StatusAccepted)
    return view(row), nil
}

func (*Ctx) StatusOf added in v0.3.0

func (c *Ctx) StatusOf() int

StatusOf returns the status that Status named, or zero.

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 ExternalDocs added in v0.3.0

type ExternalDocs struct {
	URL         string `json:"url"`
	Description string `json:"description,omitempty"`
}

ExternalDocs names a document that stands outside this one.

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 Header struct {
	// Name is the name of the header, such as Location.
	Name string `json:"name"`
	// Description states what the header holds.
	Description string `json:"description,omitempty"`
}

Header is one header that an answer carries.

type Input added in v0.3.0

type Input[T any] interface {
	*T
	Binder
	Validator
}

Input names the constraint of a type that `avero generate` prepared.

type License added in v0.3.0

type License struct {
	Name string `json:"name"`
	// Identifier is the SPDX name, such as MIT.
	Identifier string `json:"identifier,omitempty"`
	URL        string `json:"url,omitempty"`
}

License names the licence of the API.

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 NoBody added in v0.3.0

type NoBody struct{}

NoBody is the answer of a handler that carries none.

A handler returns the thing that it answers. A handler that answers nothing returns NoBody, and the router writes 204 with no body.

func (m *Module) Delete(c *avero.Ctx, in DeleteInput) (avero.NoBody, error) {
    if err := m.store.Delete(c.Context(), in.ID); err != nil {
        return avero.NoBody{}, err
    }
    return avero.NoBody{}, nil
}

type OpOption added in v0.3.0

type OpOption func(*Operation)

OpOption states one more fact of an operation.

func AnswerHeader added in v0.3.0

func AnswerHeader(code int, name, description string) OpOption

AnswerHeader states a header that one answer carries, such as Location on a 201.

func Answers added in v0.3.0

func Answers[T any](code int, description string) OpOption

Answers states one more status that the operation writes.

The success answer comes from the type of the handler, so this option states the other cases:

avero.Post(r, "/posts", m.Create, avero.Answers[Problem](409, "the title is taken"))

Two calls with one status state an answer that carries one of two shapes. The description then writes oneOf.

func AnswersNothing added in v0.3.0

func AnswersNothing(code int, description string) OpOption

AnswersNothing states one more status that the operation writes with no body.

func Deprecated added in v0.3.0

func Deprecated() OpOption

Deprecated marks an operation that a caller must leave.

func Describe added in v0.3.0

func Describe(text string) OpOption

Describe states the operation at length, where a summary is one line.

func Public added in v0.3.0

func Public() OpOption

Public states a route that needs no identity, even when the API states a scheme for every route.

func Secured added in v0.3.0

func Secured(schemes ...string) OpOption

Secured names the schemes that the route needs. The API states the schemes.

func Summary added in v0.3.0

func Summary(text string) OpOption

Summary names the operation for a person. It is one line.

func Tags added in v0.3.0

func Tags(names ...string) OpOption

Tags group the operations of a description.

type Operation added in v0.3.0

type Operation struct {
	// Method is the HTTP method of the route.
	Method string `json:"method"`
	// Pattern is the full pattern of the route.
	Pattern string `json:"pattern"`
	// Summary names the operation for a person.
	Summary string `json:"summary,omitempty"`
	// Description states the operation at length. A summary is one line, and
	// this holds the paragraph that a reader needs.
	Description string `json:"description,omitempty"`
	// Security names the schemes that the route needs. An empty list means
	// that the route follows the API.
	Security []string `json:"security,omitempty"`
	// Public states a route that needs no identity, even when the API states
	// a scheme.
	Public bool `json:"public,omitempty"`
	// Deprecated marks an operation that a caller must leave.
	Deprecated bool `json:"deprecated,omitempty"`
	// Tags group the operations of a description.
	Tags []string `json:"tags,omitempty"`
	// Handler is the name of the function that a person wrote, such as
	// posts.(*Module).List. It names the operation of the description.
	Handler string `json:"handler,omitempty"`
	// Answers holds one entry for each status that the operation writes.
	Answers []Answer `json:"answers,omitempty"`
	// contains filtered or unexported fields
}

Operation is what one route answers. The registration records it, and `avero routes --openapi` reads it from the running application.

The types come from the signature of the handler, so the compiler holds them. A comment states nothing, and a name that does not exist does not build. See the SDD, S13.

func (Operation) Input added in v0.3.0

func (o Operation) Input() reflect.Type

Input returns the type that the operation binds, or nil.

type Option

type Option func(*Router)

Option configures a router.

func WithAPI added in v0.3.0

func WithAPI(api API) Option

WithAPI states the facts of the whole description of the API.

func WithErrorResponse

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

WithErrorResponse sets the response that a handler error produces.

The default reads the Problem that the error carries and writes it as application/problem+json. See RFC 9457. An error that carries no Problem is a fault of the service, so the answer is 500 and the message stays in the log.

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 Problem added in v0.3.0

type Problem struct {
	// Type is a URI that identifies the kind of fault. The default is
	// "about:blank", which states that the status carries the whole meaning.
	Type string `json:"type,omitempty"`
	// Title is a short name of the kind of fault. It does not change between
	// two answers of the same kind.
	Title string `json:"title"`
	// Code is the HTTP status of the answer.
	Code int `json:"status"`
	// Detail explains this one answer. A person reads it.
	Detail string `json:"detail,omitempty"`
	// Instance is a URI of this one answer, such as the path of the request.
	Instance string `json:"instance,omitempty"`
	// Extensions carry the members that this kind of fault adds, such as the
	// field errors of a validation fault. RFC 9457 allows them beside the
	// members above.
	Extensions map[string]any `json:"-"`
	// contains filtered or unexported fields
}

Problem is one error of an API, in the shape that RFC 9457 states.

A handler returns it as an error, and the router writes it. One shape covers every failure of the service, so a client reads one document and the description of the API states one schema.

if !found {
    return nil, avero.NotFound("post", in.ID)
}

A Problem wraps a cause. The log reads the cause, and the client does not, so a message of the database never reaches a person outside the service.

func BadRequest added in v0.3.0

func BadRequest(detail string) *Problem

BadRequest returns the problem of a request that does not read.

func Conflict added in v0.3.0

func Conflict(detail string) *Problem

Conflict returns the problem of a state that refuses the change.

func Forbidden added in v0.3.0

func Forbidden(detail string) *Problem

Forbidden returns the problem of an identity that may not do this.

func NewProblem added in v0.3.0

func NewProblem(code int, detail string) *Problem

NewProblem returns a problem with the standard title of the status.

func NotFound added in v0.3.0

func NotFound(thing, id string) *Problem

NotFound returns the problem of a thing that the table does not hold.

return nil, avero.NotFound("post", in.ID)

func ProblemOf added in v0.3.0

func ProblemOf(err error) *Problem

ProblemOf returns the problem that an error carries.

It reads a Problem, or an error that wraps one. Every other error is a fault of the service, so the answer is 500 and the message stays in the log.

func Unauthorized added in v0.3.0

func Unauthorized(detail string) *Problem

Unauthorized returns the problem of a request with no identity.

func (*Problem) Error added in v0.3.0

func (p *Problem) Error() string

Error states the fault for a log and for errors.Is.

func (*Problem) Explain added in v0.3.0

func (p *Problem) Explain(detail string) *Problem

Explain returns a copy of the problem that carries the detail.

func (*Problem) Is added in v0.3.0

func (p *Problem) Is(target error) bool

Is reports a problem of the same status, so errors.Is(err, ErrNotFound) answers for every 404 that a handler returns.

func (*Problem) MarshalJSON added in v0.3.0

func (p *Problem) MarshalJSON() ([]byte, error)

MarshalJSON writes the members of RFC 9457 and the extensions beside them.

func (*Problem) Status added in v0.3.0

func (p *Problem) Status() int

Status returns the HTTP status of the answer.

func (*Problem) Unwrap added in v0.3.0

func (p *Problem) Unwrap() error

Unwrap returns the cause, so errors.Is and errors.As reach it.

func (*Problem) With added in v0.3.0

func (p *Problem) With(name string, value any) *Problem

With returns a copy of the problem that carries one more member.

func (*Problem) Wrap added in v0.3.0

func (p *Problem) Wrap(cause error) *Problem

Wrap returns a copy of the problem that holds the cause. The client reads the same document, and the log reads the cause.

func (*Problem) Write added in v0.3.0

func (p *Problem) Write(c *Ctx) error

Write sends the problem document.

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"`

	// Op states what the route answers. A typed registration fills it, and
	// the description of the API reads it. A plain handler leaves it nil.
	Op *Operation `json:"operation,omitempty"`
	// 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) API added in v0.3.0

func (r *Router) API() API

API returns the facts that WithAPI stated.

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 SecurityScheme added in v0.3.0

type SecurityScheme struct {
	// Type is http, apiKey, oauth2 or openIdConnect.
	Type string `json:"type"`
	// Description states the scheme for a person.
	Description string `json:"description,omitempty"`
	// Scheme is the name of an HTTP scheme, such as bearer or basic.
	Scheme string `json:"scheme,omitempty"`
	// BearerFormat names the shape of a bearer token, such as JWT.
	BearerFormat string `json:"bearerFormat,omitempty"`
	// Name is the name of the header, the query member or the cookie of an
	// apiKey scheme.
	Name string `json:"name,omitempty"`
	// In is header, query or cookie, for an apiKey scheme.
	In string `json:"in,omitempty"`
	// OpenIDConnectURL names the document of an openIdConnect scheme.
	OpenIDConnectURL string `json:"openIdConnectUrl,omitempty"`
}

SecurityScheme states how a caller proves its identity.

func APIKeyAuth added in v0.3.0

func APIKeyAuth(header, description string) SecurityScheme

APIKeyAuth returns the scheme of a key that a header carries.

func BasicAuth added in v0.3.0

func BasicAuth(description string) SecurityScheme

BasicAuth returns the scheme of a name and a password.

func BearerAuth added in v0.3.0

func BearerAuth(description string) SecurityScheme

BearerAuth returns the scheme of a bearer token.

type Server added in v0.3.0

type Server struct {
	URL         string `json:"url"`
	Description string `json:"description,omitempty"`
}

Server is one address that answers.

type Tag added in v0.3.0

type Tag struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
}

Tag describes one group of operations.

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