web

package
v0.1.0-preview.4 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Overview

Package web provides the small HTTP runtime used by generated Spice controller adapters.

Index

Constants

View Source
const (
	// DefaultMaxBodyBytes is the generated-adapter request body limit unless an
	// application selects a different positive bound.
	DefaultMaxBodyBytes int64 = 1 << 20
)

Variables

This section is empty.

Functions

func AcceptsJSON

func AcceptsJSON(header string) bool

AcceptsJSON reports whether an Accept header permits a JSON representation. An empty header accepts JSON.

func Boolean

func Boolean(location Location, name, raw string) (bool, error)

Boolean parses a Boolean parameter without retaining or reporting raw input.

func Chain

func Chain(handler http.Handler, middleware ...Middleware) (http.Handler, error)

Chain applies a deterministic middleware list around handler. Nil middleware and nil returned handlers are rejected during construction.

func DecodeForm

func DecodeForm(
	request *http.Request,
	maxBytes int64,
) (url.Values, error)

DecodeForm strictly reads one URL-encoded form within the configured bound. It does not retain the request body or mutate request.Form.

func DecodeJSON

func DecodeJSON(request *http.Request, destination any, maxBytes int64) error

DecodeJSON strictly decodes exactly one bounded application/json request body. Unknown fields and trailing values fail closed.

func Duration

func Duration(location Location, name, raw string) (time.Duration, error)

Duration parses a Go duration parameter without retaining raw input.

func FormValue

func FormValue(
	values url.Values,
	name string,
	required bool,
) (string, bool, error)

FormValue returns one optional or required form field. Repeated values fail closed because generated scalar bindings cannot choose implicitly.

func Integer

func Integer(location Location, name, raw string, bitSize int) (int64, error)

Integer parses a base-10 signed parameter with the requested Go bit width.

func Parameter

func Parameter(location Location, name string, values []string, required bool) (string, bool, error)

Parameter returns zero or one request parameter value. Required and repeated values fail with safe location-aware errors.

func Register

func Register(
	mux *http.ServeMux,
	pattern string,
	handler http.Handler,
	middleware ...Middleware,
) (err error)

Register safely registers one generated route. ServeMux reports invalid or conflicting patterns by panic; Spice converts that programmer/configuration fault into an application-construction error so cleanup rollback still runs.

func RegisterObserved

func RegisterObserved(
	mux *http.ServeMux,
	pattern string,
	handler http.Handler,
	observation Middleware,
	middleware ...Middleware,
) (err error)

RegisterObserved applies caller middleware inside one generated observation middleware, then safely registers the route. Caller middleware errors retain their original list indexes.

func RejectUnknownForm

func RejectUnknownForm(values url.Values, allowed []string) error

RejectUnknownForm rejects fields outside the generated allowlist without exposing their values.

func Validate

func Validate(ctx context.Context, validator func(context.Context) error) error

Validate invokes one generated request validator. Explicit problem errors retain their policy; ordinary validator errors become a safe 400 without exposing their text.

func WriteError

func WriteError(
	writer http.ResponseWriter,
	request *http.Request,
	err error,
	mapper ErrorMapper,
) error

WriteError maps err and writes an RFC 9457 response. A nil mapper selects the secure default.

func WriteJSON

func WriteJSON(writer http.ResponseWriter, status int, value any) error

WriteJSON writes one application/json response.

func WriteNoContent

func WriteNoContent(writer http.ResponseWriter) error

WriteNoContent writes an explicit HTTP 204 response.

func WriteProblem

func WriteProblem(writer http.ResponseWriter, problem Problem) error

WriteProblem writes one validated application/problem+json response. Invalid problem metadata is replaced with the secure internal-server problem.

Types

type BindingError

type BindingError struct {
	Location Location
	Field    string
	Reason   string
	// contains filtered or unexported fields
}

BindingError is a safe source-specific bad-request error. It intentionally records no raw request value.

func NewBindingError

func NewBindingError(location Location, field, reason string, cause error) *BindingError

NewBindingError creates a request binding failure without retaining the raw client value.

func (*BindingError) Error

func (e *BindingError) Error() string

Error renders stable request-field context.

func (*BindingError) Problem

func (e *BindingError) Problem() Problem

Problem returns a standard invalid-request problem.

func (*BindingError) Unwrap

func (e *BindingError) Unwrap() error

Unwrap returns the parser or decoder cause for server-side diagnostics.

type BindingResult

type BindingResult struct {
	// contains filtered or unexported fields
}

BindingResult is an immutable form binding and validation result. It never stores rejected raw values.

func NewBindingResult

func NewBindingResult(
	violations ...validation.Violation,
) (BindingResult, error)

NewBindingResult constructs a validated result.

func (BindingResult) Errors

func (result BindingResult) Errors() validation.Errors

Errors returns an immutable copy of the result errors.

func (BindingResult) Reject

func (result BindingResult) Reject(
	field string,
	code string,
	message string,
) (BindingResult, error)

Reject returns a new result with one additional safe violation.

func (BindingResult) RejectBinding

func (result BindingResult) RejectBinding(bindingErr error) (BindingResult, error)

RejectBinding returns a new result containing one safe request binding failure. Raw rejected values and wrapped parser errors are never retained.

func (BindingResult) Valid

func (result BindingResult) Valid() bool

Valid reports whether binding and validation succeeded.

type ErrorMapper

type ErrorMapper func(context.Context, error) Problem

ErrorMapper converts an application error into a safe problem document.

type HTTPError

type HTTPError struct {
	// contains filtered or unexported fields
}

HTTPError associates a safe problem document with an optional internal cause. The cause is available to logs through errors.Unwrap but is never included by the default response mapper.

func NewError

func NewError(problem Problem, cause error) *HTTPError

NewError creates a problem-carrying HTTP error.

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error returns stable problem context without rendering the internal cause.

func (*HTTPError) Problem

func (e *HTTPError) Problem() Problem

Problem returns the safe client-facing problem.

func (*HTTPError) Unwrap

func (e *HTTPError) Unwrap() error

Unwrap returns the internal cause.

type HTTPObserver

type HTTPObserver interface {
	BeginHTTP(context.Context, RouteMetadata) (context.Context, func(HTTPResult))
}

HTTPObserver is the dependency-free adapter point for route metrics and traces. Observers begin in declaration order and finish in reverse order.

type HTTPObserverFunc

type HTTPObserverFunc func(context.Context, RouteMetadata) (context.Context, func(HTTPResult))

HTTPObserverFunc adapts a function to HTTPObserver.

func (HTTPObserverFunc) BeginHTTP

func (observer HTTPObserverFunc) BeginHTTP(
	ctx context.Context,
	route RouteMetadata,
) (context.Context, func(HTTPResult))

BeginHTTP implements HTTPObserver.

type HTTPResult

type HTTPResult struct {
	Status   int
	Bytes    int64
	Duration time.Duration
	Panicked bool
}

HTTPResult describes one completed generated route request.

type Location

type Location string

Location identifies one request binding source.

const (
	// LocationPath identifies a route path variable.
	LocationPath Location = "path"
	// LocationQuery identifies a URL query parameter.
	LocationQuery Location = "query"
	// LocationHeader identifies an HTTP request header.
	LocationHeader Location = "header"
	// LocationBody identifies the request body.
	LocationBody Location = "body"
	// LocationForm identifies a URL-encoded form field.
	LocationForm Location = "form"
	// LocationRequest identifies whole-request typed validation.
	LocationRequest Location = "request"
)

type Middleware

type Middleware func(http.Handler) http.Handler

Middleware wraps an HTTP handler. Generated applications apply middleware in caller order: the first item observes the request first and the response last.

func ObservationMiddleware

func ObservationMiddleware(
	route RouteMetadata,
	observers ...HTTPObserver,
) (Middleware, error)

ObservationMiddleware creates one route-aware middleware after validating generated metadata and every observer.

type NoContent

type NoContent struct{}

NoContent is an explicit controller response that generates HTTP 204.

type Problem

type Problem struct {
	Type     string `json:"type"`
	Title    string `json:"title"`
	Status   int    `json:"status"`
	Detail   string `json:"detail,omitempty"`
	Instance string `json:"instance,omitempty"`
}

Problem is an RFC 9457 problem-details document.

func DefaultErrorMapper

func DefaultErrorMapper(_ context.Context, err error) Problem

DefaultErrorMapper preserves valid explicit problems and otherwise returns a generic 500 response without leaking internal error text.

func (Problem) Validate

func (p Problem) Validate() error

Validate checks the stable problem contract before a document is exposed.

type ProblemCarrier

type ProblemCarrier interface {
	Problem() Problem
}

ProblemCarrier exposes a safe client-facing problem for an error.

type RouteMetadata

type RouteMetadata struct {
	ID      string
	Module  string
	Method  string
	Pattern string
}

RouteMetadata is the stable generated identity of one HTTP route.

Jump to

Keyboard shortcuts

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