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 Delete[T any, P Input[T], V any](r *Router, pattern string, fn func(c *Ctx, in T) (V, error), opts ...OpOption)
- func Get[T any, P Input[T], V any](r *Router, pattern string, fn func(c *Ctx, in T) (V, error), opts ...OpOption)
- 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 Patch[T any, P Input[T], V any](r *Router, pattern string, fn func(c *Ctx, in T) (V, error), opts ...OpOption)
- func PathValue(r *http.Request, name string) (string, bool)
- func Post[T any, P Input[T], V any](r *Router, pattern string, fn func(c *Ctx, in T) (V, error), opts ...OpOption)
- func Put[T any, P Input[T], V any](r *Router, pattern string, fn func(c *Ctx, in T) (V, error), opts ...OpOption)
- func Register[T any, P Input[T], V any](r *Router, method, pattern string, fn func(c *Ctx, in T) (V, error), ...)
- 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 API
- type Answer
- type BindFault
- type Binder
- type Contact
- type CookieOption
- type Ctx
- func (c *Ctx) CSRFToken() string
- func (c *Ctx) Context() context.Context
- func (c *Ctx) Deadline() (time.Time, bool)
- func (c *Ctx) Done() <-chan struct{}
- func (c *Ctx) Err() error
- 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) Status(code int)
- func (c *Ctx) StatusOf() int
- 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) Value(key any) any
- func (c *Ctx) Warning(message string)
- func (c *Ctx) WriteHeader(code int)
- func (c *Ctx) Writer() http.ResponseWriter
- type ExternalDocs
- type Fault
- type Faults
- type Fields
- type Handler
- type Header
- type Input
- type License
- 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 NoBody
- type OpOption
- func AnswerHeader(code int, name, description string) OpOption
- func Answers[T any](code int, description string) OpOption
- func AnswersNothing(code int, description string) OpOption
- func Deprecated() OpOption
- func Describe(text string) OpOption
- func Public() OpOption
- func Secured(schemes ...string) OpOption
- func Summary(text string) OpOption
- func Tags(names ...string) OpOption
- type Operation
- type Option
- type Problem
- func (p *Problem) Error() string
- func (p *Problem) Explain(detail string) *Problem
- func (p *Problem) Is(target error) bool
- func (p *Problem) MarshalJSON() ([]byte, error)
- func (p *Problem) Status() int
- func (p *Problem) Unwrap() error
- func (p *Problem) With(name string, value any) *Problem
- func (p *Problem) Wrap(cause error) *Problem
- func (p *Problem) Write(c *Ctx) error
- type Report
- type Response
- type Route
- type Router
- func (r *Router) API() API
- 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) SetSummaries(docs map[string]string)
- func (r *Router) Use(mws ...Middleware)
- type SecurityScheme
- type Server
- type Stack
- type Tag
- 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 ProblemContentType = "application/problem+json"
ProblemContentType is the media type of a problem document. RFC 9457 states it.
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 ( // ErrNotFound states that the path names no thing. 404. ErrNotFound = NewProblem(http.StatusNotFound, "") 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) { ... }
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 ¶
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 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 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 ¶
RequestIDFrom returns the identifier that RequestID put in ctx. It returns the empty string when the middleware did not run.
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.
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 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 ¶
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) Deadline ¶ added in v0.4.0
Deadline reports the time at which the request context ends.
This method and the three below make *Ctx a context.Context, so a handler passes the Ctx itself to a store, to a client or to any function that takes a context. Each one reads the context of the current request, so a value that a middleware adds after the router built the Ctx is visible here.
rows, err := m.store.List(c, in.Page)
A Ctx is valid for one request, exactly as an *http.Request is. Do not hold it after the handler returns.
func (*Ctx) Done ¶ added in v0.4.0
func (c *Ctx) Done() <-chan struct{}
Done returns the channel that closes when the request context ends.
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) Status ¶ added in v0.3.0
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) 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) Value ¶ added in v0.4.0
Value returns the value that the request context carries for a key.
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 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.
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 Header ¶ added in v0.3.0
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 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 ¶
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.
Adapt watches the writer that it gives to the middleware, so the Response that it returns carries the status that the middleware wrote. The transaction middleware reads that status, so a middleware that writes a row and then answers 500 rolls back. A middleware that writes no status answers 200, as net/http does.
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
AnswerHeader states a header that one answer carries, such as Location on a 201.
func Answers ¶ added in v0.3.0
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
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
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
Secured names the schemes that the route needs. The API states the schemes.
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.
type Option ¶
type Option func(*Router)
Option configures a router.
func WithErrorResponse ¶
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 WithSummaries ¶ added in v0.3.1
WithSummaries states the summary of each handler, by the name of its method.
`avero generate` writes the map from the comment of each handler, so the description of the API carries the sentence that a person already wrote. The module set passes it before it registers the routes of a module. An option of a route wins over the map.
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 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
BadRequest returns the problem of a request that does not read.
func NewProblem ¶ added in v0.3.0
NewProblem returns a problem with the standard title of the status.
func NotFound ¶ added in v0.3.0
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
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
Unauthorized returns the problem of a request with no identity.
func (*Problem) Explain ¶ added in v0.3.0
Explain returns a copy of the problem that carries the detail.
func (*Problem) Is ¶ added in v0.3.0
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
MarshalJSON writes the members of RFC 9457 and the extensions beside them.
func (*Problem) Unwrap ¶ added in v0.3.0
Unwrap returns the cause, so errors.Is and errors.As reach it.
func (*Problem) With ¶ added in v0.3.0
With returns a copy of the problem that carries one more member.
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"`
// 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 (*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) SetSummaries ¶ added in v0.3.1
SetSummaries states the summary of each handler of the next routes. The module set calls it, so a person calls WithSummaries instead.
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 Stack ¶ added in v0.4.0
type Stack struct {
// Secret signs the CSRF cookie and the flash cookie. It is mandatory.
Secret config.Secret
// Logger writes the access log. A nil value leaves the access log out.
Logger *slog.Logger
// Trace is the middleware of the telemetry provider. A zero value leaves
// the trace out.
Trace Middleware
// Session holds the session middleware of auth-all, adapted with Adapt.
Session []Middleware
// Engine opens the transaction. A nil value leaves the transaction out,
// which an inspection command needs.
Engine *drel.Engine
// Auth holds the authentication middleware of auth-all, adapted with
// Adapt. It runs last, so it reads the session and the transaction.
Auth []Middleware
// Cookie carries the options of the two cookies that Avero owns.
Cookie []CookieOption
}
Stack builds the middleware chain of an application in the order that the SDD states, S4: request ID, recover, access log, trace, flash, session, CSRF, transaction, authentication.
The order is a correctness property. The flash middleware must read the cookie before a handler adds a toast. The transaction middleware must sit inside the session, so a rollback leaves no signed-in user without a row. A hand-written chain puts that order in every main.go, and a wrong order fails silently. Stack states it one time.
A zero field leaves its middleware out, so an application that runs no database and no authentication passes the secret alone.
r.Use(router.Stack{
Secret: cfg.Secret,
Logger: log,
Trace: provider.HTTPMiddleware(),
Engine: engine,
}.Middleware()...)
The router package must not import telemetry or auth-all, because both import the router. Trace, Session and Auth therefore carry a value that the application builds.
func (Stack) API ¶ added in v0.4.0
func (s Stack) API() []Middleware
API returns the chain of an application that answers JSON. It holds the same members in the same order, and it leaves out the two cookies that a browser form needs. A client that carries a token needs no CSRF token, and a client that reads JSON shows no toast.
The two methods make the choice a name and not a flag, so a shape that needs the CSRF token cannot lose it by a forgotten field.
func (Stack) Middleware ¶ added in v0.4.0
func (s Stack) Middleware() []Middleware
Middleware returns the chain of an application that serves a browser. It holds the flash cookie and the CSRF token, so a form posts safely and a toast crosses a redirect. The first member is the outermost one.
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.