Documentation
¶
Overview ¶
Package web provides the small HTTP runtime used by generated Spice controller adapters.
Index ¶
- Constants
- func AcceptsJSON(header string) bool
- func Boolean(location Location, name, raw string) (bool, error)
- func Chain(handler http.Handler, middleware ...Middleware) (http.Handler, error)
- func DecodeForm(request *http.Request, maxBytes int64) (url.Values, error)
- func DecodeJSON(request *http.Request, destination any, maxBytes int64) error
- func Duration(location Location, name, raw string) (time.Duration, error)
- func FormValue(values url.Values, name string, required bool) (string, bool, error)
- func Integer(location Location, name, raw string, bitSize int) (int64, error)
- func Parameter(location Location, name string, values []string, required bool) (string, bool, error)
- func Register(mux *http.ServeMux, pattern string, handler http.Handler, ...) (err error)
- func RegisterObserved(mux *http.ServeMux, pattern string, handler http.Handler, ...) (err error)
- func RejectUnknownForm(values url.Values, allowed []string) error
- func Validate(ctx context.Context, validator func(context.Context) error) error
- func WriteError(writer http.ResponseWriter, request *http.Request, err error, ...) error
- func WriteJSON(writer http.ResponseWriter, status int, value any) error
- func WriteNoContent(writer http.ResponseWriter) error
- func WriteProblem(writer http.ResponseWriter, problem Problem) error
- type BindingError
- type BindingResult
- type ErrorMapper
- type HTTPError
- type HTTPObserver
- type HTTPObserverFunc
- type HTTPResult
- type Location
- type Middleware
- type NoContent
- type Problem
- type ProblemCarrier
- type RouteMetadata
Constants ¶
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 ¶
AcceptsJSON reports whether an Accept header permits a JSON representation. An empty header accepts JSON.
func Chain ¶
Chain applies a deterministic middleware list around handler. Nil middleware and nil returned handlers are rejected during construction.
func DecodeForm ¶
DecodeForm strictly reads one URL-encoded form within the configured bound. It does not retain the request body or mutate request.Form.
func DecodeJSON ¶
DecodeJSON strictly decodes exactly one bounded application/json request body. Unknown fields and trailing values fail closed.
func FormValue ¶
FormValue returns one optional or required form field. Repeated values fail closed because generated scalar bindings cannot choose implicitly.
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 ¶
RejectUnknownForm rejects fields outside the generated allowlist without exposing their values.
func Validate ¶
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 ¶
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 (*HTTPError) Error ¶
Error returns stable problem context without rendering 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 ¶
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 ¶
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 ¶
DefaultErrorMapper preserves valid explicit problems and otherwise returns a generic 500 response without leaking internal error text.
type ProblemCarrier ¶
type ProblemCarrier interface {
Problem() Problem
}
ProblemCarrier exposes a safe client-facing problem for an error.