gorestapi

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2026 License: BSD-2-Clause Imports: 34 Imported by: 0

README

gorestapi

Package gorestapi mounts a ready-made JSON REST API on top of a gocrud registry. A single handler covers list, read, create, update, and delete for every route you register — with no code generation and no framework lock-in.

Documentation

Development

  • scripts/test.sh checks the formatting, and runs go vet and the tests. The tests start PostgreSQL in docker.
  • scripts/concurcheck.sh runs the tests with the race detector, and checks that no goroutines are still running after the tests of each package.
  • scripts/lint.sh runs the static analysis: golangci-lint, with the linters of .golangci.yml, which include gosec, and gosec itself, also on the tests.
  • scripts/vulncheck.sh checks the code and the dependencies for known vulnerabilities with govulncheck.

The scripts check the demo in cmd/poc too, which is a Go module of its own.

The GitHub workflows run the tests, the static analysis and the vulnerability check on pull requests and on main, and the vulnerability check also every Monday, as new vulnerabilities are found without any change of the code. Dependabot proposes updates of the dependencies and of the actions every week.

Documentation

Index

Constants

View Source
const (
	CodeServiceError = "SERVICE_ERROR"
	CodeNotAllowed   = "NOT_ALLOWED"
	CodeForbidden    = "FORBIDDEN"
)
View Source
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
)
View Source
const (
	DefaultMaxFilters  = 20
	DefaultMaxInValues = 100
	DefaultTimeout     = 30 * time.Second
)

The limits of a request when Options does not set them.

View Source
const CodeServiceUnavailable = "SERVICE_UNAVAILABLE"

CodeServiceUnavailable is the code of the problem of a readiness probe whose check fails.

View Source
const CodeTooManyRequests = "TOO_MANY_REQUESTS"

CodeTooManyRequests is the code of the problem of a request over the limit of Options.RateLimiter.

View Source
const CodeUnauthorized = "UNAUTHORIZED"

CodeUnauthorized is the code of the problem of a request without valid credentials, see Options.Authenticate.

View Source
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

View Source
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

func BearerToken(r *http.Request) (string, bool)

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

func ClientIP(r *http.Request, trustedProxies []netip.Prefix) netip.Addr

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

func ClientIPKey(addr netip.Addr) string

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

func LogHandler(next slog.Handler) slog.Handler

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.

func Principal

func Principal(ctx context.Context) any

Principal returns the principal of the request of ctx, from Options.Authenticate, e.g. the claims of its token, or nil for a request without one, e.g. of a route with Anonymous.

func RequestID

func RequestID(ctx context.Context) string

RequestID returns the ID of the request of ctx, or an empty string for a context of no request of the handler.

Types

type FilterSet

type FilterSet struct {
	Vals map[string]string
	Ops  map[string]string
}

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 New

func New(reg Registry, options Options) *Handler

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

func (h *Handler) Readiness(check func(ctx context.Context) error) http.HandlerFunc

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

func (h *Handler) RoutePath(r *http.Request) string

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.

func (*Handler) Serve

func (h *Handler) Serve(w http.ResponseWriter, r *http.Request)

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.

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.

Jump to

Keyboard shortcuts

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