httpx

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 19 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package httpx is the JSON API plumbing a handler needs: reading and checking a request, and writing results and errors.

Index

Constants

View Source
const MaxBatch = 100

MaxBatch is the most requests one batch may hold.

Variables

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

func BoolParam(v, name string) (bool, error)

BoolParam reads a true/false query parameter called name; absent is false.

func CORS

func CORS(allow func(origin string) bool, next http.Handler) http.Handler

CORS answers a browser's cross-origin request, and its preflight, for an origin that allow accepts. Other requests pass through untouched.

func Decode

func Decode(body []byte, dst any) error

Decode reads a JSON body into dst, refusing unknown fields.

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 DryRun

func DryRun(r *http.Request) bool

DryRun reports whether the request asked for a dry run.

func FieldsOf

func FieldsOf(q map[string][]string) []string

FieldsOf is the fields parameter split on commas, nil when absent.

func First

func First(q map[string][]string, k string) string

First is the first value of a query parameter, "" when absent.

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 Marshal

func Marshal(v any) ([]byte, error)

Marshal encodes v as JSON without HTML escaping or a trailing newline.

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

func OriginAllowed(patterns []string, origin string) bool

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 Project

func Project(v any, fields []string) (any, error)

Project keeps only fields of v, or of each item when v is a page.

func ProjectBytes

func ProjectBytes(b []byte, fields []string) ([]byte, error)

ProjectBytes is Project over encoded JSON.

func Query

func Query(r *http.Request, allowed ...string) (map[string][]string, error)

Query returns the query parameters, refusing any not in allowed.

func RequestHash

func RequestHash(method, path, rawQuery string, body []byte) string

RequestHash identifies a request for idempotency replay.

func VersionParam

func VersionParam(r *http.Request) (int, error)

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.

func WriteRaw

func WriteRaw(w http.ResponseWriter, status int, b []byte)

WriteRaw writes encoded JSON as a response.

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.

func (Trace) Wrap

func (t Trace) Wrap(next http.Handler) http.Handler

Jump to

Keyboard shortcuts

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