Documentation
¶
Index ¶
- Constants
- Variables
- func Bearer(verify func(ctx context.Context, token string) (any, error)) func(r *http.Request) (any, error)
- func BearerToken(r *http.Request) (string, bool)
- func ClientIP(r *http.Request, trustedProxies []netip.Prefix) netip.Addr
- func ClientIPKey(addr netip.Addr) string
- func Liveness(w http.ResponseWriter, _ *http.Request)
- func LogHandler(next slog.Handler) slog.Handler
- func Principal(ctx context.Context) any
- func RequestID(ctx context.Context) string
- type FilterSet
- type Handler
- type OpenAPIInfo
- type Options
- type RateLimiter
- type Registry
- type Route
Constants ¶
const ( CodeServiceError = "SERVICE_ERROR" CodeNotAllowed = "NOT_ALLOWED" CodeForbidden = "FORBIDDEN" )
const ( DisableCreate = 1 << iota DisableUpdate DisableDelete DisableRead DisableList DisableFilters // EnableMatchFilters allows the match operator, a regular expression, which can take the database a long time. EnableMatchFilters )
const ( DefaultMaxFilters = 20 DefaultMaxInValues = 100 DefaultTimeout = 30 * time.Second )
The limits of a request when Options does not set them.
CodeServiceUnavailable is the code of the problem of a readiness probe whose check fails.
const CodeTooManyRequests = "TOO_MANY_REQUESTS"
CodeTooManyRequests is the code of the problem of a request over the limit of Options.RateLimiter.
CodeUnauthorized is the code of the problem of a request without valid credentials, see Options.Authenticate.
const RequestIDHeader = "X-Request-ID"
RequestIDHeader is the header of the ID of a request, which the handler reads from the request, or generates, and writes to the response.
Variables ¶
var ErrNoCredentials = errors.New("no credentials")
ErrNoCredentials is returned by an Authenticate for a request without credentials, e.g. without an Authorization header. It lets the requests of the routes with Anonymous through, and its problem UNAUTHORIZED has the header WWW-Authenticate: Bearer, without the error="invalid_token" of other errors, as RFC 6750 says.
Functions ¶
func Bearer ¶
func Bearer(verify func(ctx context.Context, token string) (any, error)) func(r *http.Request) (any, error)
Bearer returns an Authenticate of the tokens of the Authorization: Bearer header, e.g. JWTs or PASETOs: verify returns the principal of a token, e.g. its claims, or an error for a token that is not valid. A request without a token is ErrNoCredentials.
func BearerToken ¶
BearerToken returns the token of the Authorization: Bearer header of r, or false when it has none. Tokens are read only from the header, not from the URL, which is kept in logs and the history of browsers.
func ClientIP ¶
ClientIP returns the IP of the client of r: the IP of its connection, or, when it is one of trustedProxies, e.g. of a load balancer, the last IP of its X-Forwarded-For header that is not of a trusted proxy. The header of other clients is not read, as they can send any IP in it.
func ClientIPKey ¶
ClientIPKey returns the key of the rate limit of an IP: the IP, or its network /64 for IPv6, as a client usually has a whole /64, and could change its IP in it for every request.
func Liveness ¶
func Liveness(w http.ResponseWriter, _ *http.Request)
Liveness is the handler of a probe of liveness, e.g. /healthz of Kubernetes: it responds 200 while the process serves requests. It does not check the database, as a restart of the process would not fix it.
func LogHandler ¶
LogHandler returns a handler of slog that adds the request_id attribute, the ID of the request of the context, to the records of next, e.g. of the handler, of the registry and of the hooks, which log with the context of the request, and the trace_id and span_id attributes of its span of OpenTelemetry, when it is recorded.
Types ¶
type FilterSet ¶
FilterSet holds server-side filters injected independently of client input. Ops maps field names to op strings ("eq", "ne", "lt", …); an absent entry defaults to "eq".
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
func (*Handler) OpenAPI ¶
func (h *Handler) OpenAPI(info OpenAPIInfo) ([]byte, error)
OpenAPI returns the OpenAPI 3.0 document of the routes of the handler, as JSON: the operations that the routes allow, their parameters, e.g. the filters of the lists, the schemas of the structs of the records, with their validation rules, and the problems of their errors.
func (*Handler) Readiness ¶
Readiness returns the handler of a probe of readiness, e.g. /readyz of Kubernetes: it responds 200 when check returns nil, e.g. db.PingContext, and the problem SERVICE_UNAVAILABLE otherwise, so that no requests are sent to the process until it can serve them. The check gets the context of the request, with the Timeout of the options.
func (*Handler) RoutePath ¶
RoutePath returns the path of the route of r, a key of Options.Routes, e.g. "notes" for /notes/42, or an empty string when r is not for any of them. It has few values, e.g. for the labels of the metrics of the requests, unlike the path of r, which has the IDs, and any path that a client sends.
type OpenAPIInfo ¶
type OpenAPIInfo struct {
Title string
Version string
Description string
// Servers are the URLs of the API, with the prefix of its mount, e.g. https://api.example.com/api or /api.
Servers []string
// BearerFormat is the format of the tokens of Options.Authenticate, e.g. JWT, a hint for the clients.
BearerFormat string
}
OpenAPIInfo describes the API in its OpenAPI document.
type Options ¶
type Options struct {
// Authenticate returns the principal of a request, e.g. the claims of its token, which the hooks and UserIDFunc
// get with Principal(r.Context()), or an error, which is the problem UNAUTHORIZED, e.g. ErrNoCredentials for a
// request without credentials, see Bearer. It is called with every request of a route, except OPTIONS, before its
// operation. When it is nil, the requests are not authenticated.
Authenticate func(r *http.Request) (any, error)
// RateLimiter limits the requests of each client, after they are authenticated, e.g. NewRateLimiter(10, 20). A
// request over the limit is the problem TOO_MANY_REQUESTS. It is nil for no limit.
RateLimiter RateLimiter
// RateLimitKey returns the key of the limit of a request, e.g. the user of its Principal, or ClientIPKey of its
// ClientIP, which is the key when it is nil.
RateLimitKey func(r *http.Request) string
// TrustedProxies are the networks of the proxies in front of the API, e.g. of its load balancer, whose
// X-Forwarded-For header has the IP of the client, see ClientIP.
TrustedProxies []netip.Prefix
// DisableSecurityHeaders leaves out the headers of security of the responses: X-Content-Type-Options: nosniff,
// X-Frame-Options: DENY, Content-Security-Policy: default-src 'none'; frame-ancestors 'none', Referrer-Policy:
// no-referrer and Cache-Control, e.g. when a proxy in front of the API sets them.
DisableSecurityHeaders bool
// CacheControl is the Cache-Control header of the responses, no-store when it is empty, so that the records of a
// user are not kept by browsers and proxies. Set it e.g. to "public, max-age=60" for an API of public data.
CacheControl string
// HSTSMaxAge sends the Strict-Transport-Security header, with includeSubDomains, so that browsers use only HTTPS
// for the domain for this long, e.g. a year. It is not sent when it is 0, e.g. when the proxy that ends TLS sends
// it, as it should be sent only over HTTPS.
HSTSMaxAge time.Duration
// MaxBodyBytes is the largest body of a create or an update, jsonreq.DefaultMaxBytes (1 MiB) when it is 0, and no
// limit when it is negative. A larger body is the problem REQUEST_TOO_LARGE.
MaxBodyBytes int64
// AllowUnknownFields ignores the fields of the body of a create or an update that the struct does not have,
// instead of the problem VALIDATION_FAILED, e.g. for clients that send the fields of a newer version.
AllowUnknownFields bool
// ProblemTypeBaseURL is the beginning of the type URIs of the problems of the error responses, e.g.
// https://api.example.com/problems/, followed by the code of the problem, e.g. unique-violation. When it is empty,
// the type of all the problems is about:blank, and their code tells them apart.
ProblemTypeBaseURL string
// Logger logs the errors of the hooks of the routes, and the problems of the routes, or slog.Default() when it is
// nil. The errors of the queries are logged by the registry, see registry.CRUD.WithLogger.
Logger *slog.Logger
// TracerProvider and MeterProvider are the providers of OpenTelemetry of the spans and the metrics of the requests,
// or the global ones, of otel.SetTracerProvider and otel.SetMeterProvider, when they are nil.
TracerProvider trace.TracerProvider
MeterProvider metric.MeterProvider
// AccessLog logs every request with Logger, at the info level: its method, route, path, the status and the size of
// its response, and its duration.
AccessLog bool
Routes map[string]Route
// UserIDFunc is called on every create and update request to obtain the
// current user's ID, which is passed to the registry as ModifiedBy: a
// uint64, or a string for CreatedBy and ModifiedBy fields of type string.
// When nil, or when it returns nil, ModifiedBy is the zero value.
UserIDFunc func(r *http.Request) any
// MaxFilters is the largest number of the filters of a list request: DefaultMaxFilters when it is 0, and no
// limit when it is negative.
MaxFilters int
// MaxInValues is the largest number of the values of an in filter: DefaultMaxInValues when it is 0, and no limit
// when it is negative.
MaxInValues int
// Timeout is the longest time of the queries of a request, which are cancelled after it: DefaultTimeout when it
// is 0, and no timeout when it is negative.
Timeout time.Duration
}
type RateLimiter ¶
type RateLimiter interface {
// Allow returns whether a request of key can be served now, or how long until the next one can be.
Allow(ctx context.Context, key string) (bool, time.Duration, error)
}
RateLimiter limits the requests of each key, e.g. of an IP of a client, see Options.RateLimiter. NewRateLimiter keeps the limits in the memory of the process, and an implementation with e.g. Redis shares them between the instances of the API.
func NewRateLimiter ¶
func NewRateLimiter(perSecond float64, burst int) RateLimiter
NewRateLimiter returns a RateLimiter of the memory of the process, which serves perSecond requests of each key, and up to burst requests at once, e.g. 10 a second, with bursts of 20.
type Registry ¶
type Registry interface {
New(key string) any
ID(obj any) any
Read(ctx context.Context, key string, id any, constructor func() any) (any, error)
List(ctx context.Context, key string, options registry.ListOptions) ([]any, error)
NextCursor(obj any, order string, orderDirection string) (string, error)
Save(ctx context.Context, obj any, userID any) error
Delete(ctx context.Context, key string, id any) error
PasswordFieldNames(key string) []string
RelatedType(obj any, field string) (reflect.Type, bool)
}
Registry is what the handler needs of a registry of structs. *registry.CRUD of gocrud implements it, and so can a layer of the application in front of it, e.g. with the rules of its domain, or a fake in tests. The handler maps the errors of the registry to its responses, so an implementation returns the same errors, e.g. a *registry.ModelValidationError for an invalid record, or an error that matches gocrud.ErrNotFound.
type Route ¶
type Route struct {
RegistryKey string
Flags int64
// AllowedFilters lists the fields and paths that clients may use in filters. When it is empty, the fields that
// List returns are allowed, i.e. not the password fields and the fields with a json:"-" tag, and no paths. The
// order can be a field that List returns, or one of AllowedFilters.
AllowedFilters []string
// Anonymous serves the requests of the route without credentials, with no Principal, when Options.Authenticate
// returns ErrNoCredentials, e.g. for the public records of a catalog. Requests with credentials that are not valid
// are still the problem UNAUTHORIZED.
Anonymous bool
// Allow hooks — called with the object and request; return non-nil to reject
// with 403. AllowUpdate receives the loaded record before the request body is
// applied, so it reflects the stored state (e.g. the original owner).
AllowCreate func(obj any, r *http.Request) error
AllowUpdate func(obj any, r *http.Request) error
AllowRead func(obj any, r *http.Request) error
AllowDelete func(obj any, r *http.Request) error
// Pre hooks — called with the fully prepared object just before it is saved;
// the request body has already been applied and the ID is set. Return non-nil
// to abort the operation with 500.
PreCreate func(obj any, r *http.Request) error
PreUpdate func(obj any, r *http.Request) error
// PostRead is called on a single loaded record before it is serialised to
// JSON. Return non-nil to abort with 500.
PostRead func(obj any, r *http.Request) error
// PostListItem is called on each item in a list response before it is
// serialised to JSON. Return non-nil to abort the entire list with 500.
PostListItem func(obj any, r *http.Request) error
// FilterList returns server-side filters applied to every list request.
// They are joined with AND around the client's filters, so clients cannot
// override them or widen them with filter groups.
FilterList func(r *http.Request) FilterSet
// FilterRead returns server-side filters applied when reading a single
// record by ID. The handler calls List(limit=1) with these filters and
// the ID; a mismatch returns 404 so record existence is not revealed to
// unauthorised callers.
FilterRead func(r *http.Request) FilterSet
// Per-operation constructor overrides. When nil the registry's registered
// constructor for the key is used. Set to use a different struct type for
// a specific operation — for example a create-only struct with fewer fields
// that implements a custom insertQueryBuilder.
CreateConstructor func() any
UpdateConstructor func() any
ReadConstructor func() any
ListConstructor func() any
}
Route maps a URL path segment to a registry key and configures per-operation behavior. When RegistryKey is empty the URL path segment is used as the registry key.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
fixtures
Package fixtures has the TestStruct struct of the tests, with the checks of its rows in the database.
|
Package fixtures has the TestStruct struct of the tests, with the checks of its rows in the database. |
|
pkg
|
|
|
jsonreq
Package jsonreq decodes the JSON bodies of requests strictly: of a JSON content type, of a limited size, with no fields that the value does not have, and with nothing after the value.
|
Package jsonreq decodes the JSON bodies of requests strictly: of a JSON content type, of a limited size, with no fields that the value does not have, and with nothing after the value. |