Documentation
¶
Overview ¶
Package httpx is the JSON API plumbing a handler needs: reading and checking a request, and writing results and errors.
Index ¶
- Constants
- Variables
- func Batch(h http.Handler, w http.ResponseWriter, r *http.Request, body []byte, ...)
- func BoolParam(v, name string) (bool, error)
- func CORS(allow func(origin string) bool, next http.Handler) http.Handler
- func Decode(body []byte, dst any) error
- func DeleteOne(st IdemStore, w http.ResponseWriter, r *http.Request, ...)
- func DryRun(r *http.Request) bool
- func FieldsOf(q map[string][]string) []string
- func First(q map[string][]string, k string) string
- func GetOne(w http.ResponseWriter, r *http.Request, allowed []string, ...)
- func Marshal(v any) ([]byte, error)
- func Mutate(st IdemStore, w http.ResponseWriter, r *http.Request, status int, ...)
- func OriginAllowed(patterns []string, origin string) bool
- func PageSlice[T any](w http.ResponseWriter, r *http.Request, fieldAllow []string, ...)
- func Project(v any, fields []string) (any, error)
- func ProjectBytes(b []byte, fields []string) ([]byte, error)
- func Query(r *http.Request, allowed ...string) (map[string][]string, error)
- func RequestHash(method, path, rawQuery string, body []byte) string
- func VersionParam(r *http.Request) (int, error)
- func WriteErr(w http.ResponseWriter, err error)
- func WriteJSON(w http.ResponseWriter, status int, v any)
- func WriteProjected(w http.ResponseWriter, status int, v any, fields []string)
- func WriteRaw(w http.ResponseWriter, status int, b []byte)
- type IdemRecord
- type IdemStore
- type Trace
Constants ¶
const MaxBatch = 100
MaxBatch is the most requests one batch may hold.
Variables ¶
var ErrIdempotencyRace = errors.New("idempotency race")
ErrIdempotencyRace means another request claimed the key first.
Functions ¶
func Batch ¶ added in v0.3.0
func Batch(h http.Handler, w http.ResponseWriter, r *http.Request, body []byte, refuse func(path string) bool)
Batch answers a batch route: body lists requests, and each runs through h as a direct call would, with the batch request's context (so the same actor), which makes scopes, validation, idempotency and dry-run apply per item. Items run in order and are not atomic. A path outside /v1/, the batch route itself, or one refuse reports is answered 400 without being run. ponytail: sequential and non-atomic; wrap in one tx if partial batches bite.
func BoolParam ¶ added in v0.3.0
BoolParam reads a true/false query parameter called name; absent is false.
func CORS ¶
CORS answers a browser's cross-origin request, and its preflight, for an origin that allow accepts. Other requests pass through untouched.
func DeleteOne ¶ added in v0.3.0
func DeleteOne(st IdemStore, w http.ResponseWriter, r *http.Request, fn func(ctx context.Context, id string, version int) (any, error))
DeleteOne answers a delete of the record named by the {id} path value. The caller must name the version it saw (see VersionParam).
func GetOne ¶ added in v0.3.0
func GetOne(w http.ResponseWriter, r *http.Request, allowed []string, load func(ctx context.Context, id string) (any, error))
GetOne answers a read of the record named by the {id} path value, honoring ?fields.
func Mutate ¶
func Mutate(st IdemStore, w http.ResponseWriter, r *http.Request, status int, allowed []string, body []byte, fn func(ctx context.Context) (any, error))
Mutate runs a write and answers with its result. It honors ?fields, a dry run (fn runs in a transaction that is rolled back), and Idempotency-Key: a repeat of the same request replays the stored response, and the same key on a different request is refused.
func OriginAllowed ¶
OriginAllowed reports whether origin matches one of the patterns: "*", an exact origin, or a prefix ending in "*".
func PageSlice ¶ added in v0.3.0
func PageSlice[T any](w http.ResponseWriter, r *http.Request, fieldAllow []string, load func(context.Context) ([]T, error), params ...string)
PageSlice answers a list the app loads whole. Without ?limit it returns every row; with it, it pages by offset. params are the query parameters the route takes besides limit, cursor and fields. A nil fieldAllow means the response takes no ?fields. ponytail: offset cursor over an in-memory slice, fine for short lists; use paging.Request with SQL keyset paging for one that grows large.
func ProjectBytes ¶
ProjectBytes is Project over encoded JSON.
func RequestHash ¶
RequestHash identifies a request for idempotency replay.
func VersionParam ¶
VersionParam is the version from the query or the If-Match header.
func WriteErr ¶
func WriteErr(w http.ResponseWriter, err error)
WriteErr writes err as the JSON error envelope. Anything that is not an apperr.Error is logged and answered as a 500.
func WriteJSON ¶
func WriteJSON(w http.ResponseWriter, status int, v any)
WriteJSON writes v as a JSON response.
func WriteProjected ¶
func WriteProjected(w http.ResponseWriter, status int, v any, fields []string)
WriteProjected writes v as JSON, keeping only fields when any are given.
Types ¶
type IdemRecord ¶
type IdemRecord struct {
TokenID string
UserID string
Key string
Method string
Path string
RequestHash string
StatusCode int
ResponseBody string
CreatedAt time.Time
}
IdemRecord is one Idempotency-Key a token has used. StatusCode is 0 while the first request is still running.
type IdemStore ¶
type IdemStore interface {
WithTx(ctx context.Context, fn func(context.Context) error) error
GetIdempotency(ctx context.Context, tokenID, key string) (IdemRecord, bool, error)
InsertIdempotency(ctx context.Context, rec IdemRecord) error
FinishIdempotency(ctx context.Context, tokenID, key string, status int, body string) error
}
IdemStore keeps idempotency records. InsertIdempotency answers ErrIdempotencyRace when the key already exists.
type Trace ¶
type Trace struct {
// Log returns the logger for a request.
Log func() *slog.Logger
// OnFailure, when set, sees every panic (v != nil) and every 5xx response.
OnFailure func(r *http.Request, requestID string, status int, v any)
}
Trace gives every request an X-Request-Id, logs it when it ends, and turns a panic into a 500.