Repository navigation
Expand file tree
/
Copy pathdoc.go
More file actions
42 lines (42 loc) · 2.2 KB
/
Copy pathdoc.go
File metadata and controls
42 lines (42 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Package apihandler provides small, composable building blocks for JSON
// HTTP APIs: a Resolver loads the domain object addressed by a request; a
// Creator, Updater, or Deleter ("Hydrator") mutates it; and a Transformer
// converts it into the representation the client receives. It is a Go port
// of the mental model behind the PHP package wickedbyte/api-handler.
//
// Handlers built from these roles return a Result value instead of writing
// to an http.ResponseWriter. The Writer is the component that turns a Result
// (or an error) into a real HTTP response, encoding the body as JSON,
// rendering errors as RFC 9457 problem+json, and logging each error it
// handles with log/slog, by default.
//
// # Lazy bodies
//
// A Result's Body is lazy Content: the domain object is not transformed
// into its response representation until the Writer asks for it. Middleware
// between a CRUD handler and the Writer can therefore still reach the
// untransformed domain object (via the Resourcer interface) or decorate the
// eventual representation (via MapBody) before any serialization happens.
//
// See Content and Resource for the evaluation contract: bodies must be
// side-effect-free and safe to evaluate more than once, and must be
// evaluated before the handler's request ends (Writer does this).
//
// # Decorating bodies safely
//
// Decorating a body by hand carries a footgun: assigning to res.Body a
// ContentFunc whose closure reads res.Body again captures the field, not
// the previous body, and recurses forever when the content is finally
// requested. If you decorate by hand, capture the previous body in a local
// variable first. Better, use MapBody: it captures correctly, is a no-op on
// bodiless results, and preserves the Resourcer view of the wrapped body so
// stacked decorators never cost middleware its access to the domain object.
//
// # Contexts
//
// The role interfaces receive the *http.Request rather than a bare
// context.Context: the request is the context carrier, and implementations
// typically also need r.PathValue, the query string, or headers.
// Implementations that call into a data layer must propagate r.Context()
// so cancellation and deadlines reach downstream work.
package apihandler