handler

package
v2.0.0-beta.6 Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package handler is chok's typed request layer: generic HandleRequest / HandleAction / HandleList constructors that bind path + query + JSON sources into one request struct, validate it, call the business function and render the uniform success / apierr envelope. Since M2 the whole layer is stdlib-only — handlers are plain http.Handler values; route metadata rides on the handler itself via Meta() (consumed by the web route table, SPEC §4.2).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AutoSummary

func AutoSummary(method, path string) string

AutoSummary derives a summary from the HTTP method and path.

POST /api/v1/posts        → "Create posts"
GET  /api/v1/posts        → "List posts"
GET  /api/v1/posts/{rid}  → "Get posts"
PUT  /api/v1/posts/{rid}  → "Update posts"
DELETE /api/v1/posts/{rid} → "Delete posts"

func AutoTags

func AutoTags(path string) []string

AutoTags derives tags from the path — the last non-parameter segment.

/api/v1/posts        → ["posts"]
/api/v1/posts/{rid}  → ["posts"]

func HandleAction

func HandleAction[T any](h ActionFunc[T], opts ...HandleOption) http.Handler

HandleAction creates an http.Handler for actions (no response body, 204 by default).

func HandleList

func HandleList[T any](lister QueryLister[T], opts ...HandleOption) http.Handler

HandleList creates an http.Handler that parses page/size/order/filter from URL query parameters and returns a paginated ListResult.

Supported query params (parsed by where.FromQuery):

page   — page number (default 1)
size   — items per page (default 20)
order  — "field:asc" or "field:desc"
<field> — equality filter (field must be in WithQueryFields)

Usage:

r.Handle("GET", "/posts", handler.HandleList(postStore))

func HandleRequest

func HandleRequest[T any, R any](h HandlerFunc[T, R], opts ...HandleOption) http.Handler

HandleRequest creates an http.Handler with multi-source binding. Tag analysis happens once at construction time.

func WriteError

func WriteError(w http.ResponseWriter, r *http.Request, err error)

WriteError renders err through the apierr pipeline: resolve to *apierr.Error, run render hooks on a per-response copy, emit headers and the uniform envelope. Same written-guard as WriteResponse.

func WriteResponse

func WriteResponse(w http.ResponseWriter, r *http.Request, code int, data any, err error)

WriteResponse writes a success or error JSON response.

Success: HTTP {code}, body = data. Error: HTTP {apierr.Code}, body = ErrorResponse with request_id from ctx.

No-op when the response has already been written (e.g. a timeout middleware already wrote 504). Without this guard, a recovered panic in a later handler would trigger "http: superfluous response.WriteHeader call" warnings and produce a garbled body.

Types

type ActionFunc

type ActionFunc[T any] func(ctx context.Context, req *T) error

ActionFunc is a typed handler that returns only an error (no response body).

func ValidatedAction

func ValidatedAction[T any](h ActionFunc[T], validators ...validate.Func[T]) ActionFunc[T]

ValidatedAction wraps an ActionFunc with additional validation functions. Same error wrapping as Validated.

type Binder

type Binder interface {
	// Tag returns the struct tag this binder handles (e.g., "uri", "form", "json").
	Tag() string
	// Bind maps values from the request into the target struct. w is
	// available for body-limit enforcement (http.MaxBytesReader).
	Bind(w http.ResponseWriter, r *http.Request, target any) error
}

Binder binds a specific source (URI params, query string, JSON body, etc.) into struct fields tagged with the corresponding struct tag. Bind must NOT run validation — validation runs once after all binders complete.

type ErrorResponse

type ErrorResponse struct {
	Code      int            `json:"code"`
	Reason    string         `json:"reason"`
	Message   string         `json:"message"`
	RequestID string         `json:"request_id,omitempty"`
	Metadata  map[string]any `json:"metadata,omitempty"`
}

ErrorResponse is the JSON body for error responses.

type HandleOption

type HandleOption func(*handleConfig)

HandleOption controls handler behavior.

func WithBinders

func WithBinders(binders ...Binder) HandleOption

WithBinders appends additional binders to the default set (uri, query, json). Custom binders run after the built-in ones, in the order provided.

func WithMaxBodySize

func WithMaxBodySize(n int64) HandleOption

WithMaxBodySize overrides the default 4 MiB request-body cap for this handler. Use for upload endpoints or webhook receivers that legitimately accept larger payloads. Non-positive values are ignored (default kept).

func WithPublic

func WithPublic() HandleOption

WithPublic marks this handler as not requiring authentication. In OpenAPI output, the route omits the security requirement so clients know no Bearer token is needed (e.g. login, register).

func WithSuccessCode

func WithSuccessCode(code int) HandleOption

WithSuccessCode overrides the default success HTTP status code.

func WithSummary

func WithSummary(s string) HandleOption

WithSummary sets the OpenAPI summary for this handler (optional). If not set, auto-derived from HTTP method + path.

func WithTags

func WithTags(tags ...string) HandleOption

WithTags sets the OpenAPI tags for this handler (optional). If not set, auto-derived from path resource name.

type HandlerFunc

type HandlerFunc[T any, R any] func(ctx context.Context, req *T) (R, error)

HandlerFunc is a typed handler that returns a response and error.

func Validated

func Validated[T any, R any](h HandlerFunc[T, R], validators ...validate.Func[T]) HandlerFunc[T, R]

Validated wraps a HandlerFunc with additional validation functions. If a validator returns a plain error (not *apierr.Error), it is automatically wrapped as ErrInvalidArgument so it always produces a 4xx response.

type ListResult

type ListResult[T any] struct {
	Items   []T   `json:"items"`
	Total   int64 `json:"total"`
	Page    int   `json:"page,omitempty"`
	Size    int   `json:"size,omitempty"`
	HasMore bool  `json:"has_more"`
}

ListResult is the standard paginated response wrapper. When page/size are parsed from the query, Page and Size are populated so clients can compute total pages without extra logic.

type Meta

type Meta struct {
	ReqType  reflect.Type // request struct type (nil for HandleList)
	RespType reflect.Type // response type (nil for ActionFunc)
	Code     int          // success HTTP status code
	Summary  string       // user-provided or auto-derived
	Tags     []string     // user-provided or auto-derived
	IsList   bool         // true for HandleList
	Public   bool         // true = no auth required (omits security in OpenAPI)
}

Meta is the route metadata a constructed handler carries: request / response types for schema generation plus the documentation knobs. HandleRequest / HandleAction / HandleList attach it to the returned http.Handler; the web router type-asserts `interface{ Meta() Meta }` (aliased as web.HandlerMeta) at registration time and records it in the route table — this replaces v1's unsafe closure-address registry wholesale (SPEC §4.2 item 1).

type QueryLister

type QueryLister[T any] interface {
	ListFromQuery(ctx context.Context, query url.Values) (*where.Page[T], error)
}

QueryLister is implemented by store.Store[T] (and wrappers that embed it). The interface decouples handler from store — handler never imports the store package; where.Page (aliased as store.Page) lives in the query layer both already speak. Page.Meta is the pagination the query actually executed with; HandleList renders the envelope from it instead of re-deriving values from the raw request.

Jump to

Keyboard shortcuts

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