Documentation
¶
Overview ¶
Package http contains HTTP specific constructs that complement the code generated by Loom. The constructs include a composable HTTP client, default encodings, a mux and a websocket implementation that relies on the Gorilla websocket package.
Index ¶
- Constants
- Variables
- func AddRequestCookie(req *http.Request, name, value string) error
- func AddRequestCookieParam(req *http.Request, name string, codec ParamCodec, value ParamValue, ...) error
- func AsHandlerFunc(handler http.Handler) http.HandlerFunc
- func CORSHandler(policy CORSPolicy, next http.HandlerFunc) http.HandlerFunc
- func CORSOptionsHandler(policy CORSPolicy, next http.HandlerFunc, allowedMethods []string) http.HandlerFunc
- func CheckFinalStatus(keys []StatusSelector, selector StatusSelector, code int, hasBody bool) error
- func DecodeFormValue(values url.Values, prefix string, target any) (bool, error)
- func DecodeFormValues(values url.Values, target any) error
- func DecodeJSONField(values url.Values, name string, target any, allowNull bool, ...) (bool, error)
- func DecodeMediaRequest(request *http.Request, target any, allowsNull bool, parts map[string]string, ...) error
- func DecodeMediaResponse(response *http.Response, target any, allowsNull bool, parts map[string]string, ...) error
- func DecodeMultipartBinary(form *MultipartForm, name string, target any, application FieldApplication) (bool, error)
- func DecodeMultipartJSON(form *MultipartForm, name string, target any, allowsNull bool, ...) (bool, error)
- func DecodeMultipartRequestWithLimit(req *http.Request, maxBytes int64, decode func(*multipart.Reader) error) error
- func DecodePathArray(raw string) ([]string, error)
- func DecodeResponse(resp *http.Response, restoreBody, streamBody bool, ...) (result any, err error)
- func DefaultProblemTitle(code string, status int) string
- func DefaultProblemTypeURI(code string) string
- func DerivedHeadHandler(next http.Handler) http.Handler
- func EffectiveClientAddress(r *http.Request) string
- func EncodeFormValue(values url.Values, prefix string, v any) (bool, error)
- func EncodeFormValues(v any) (url.Values, error)
- func EncodeHeaderParam(name string, codec ParamCodec, value ParamValue) (string, error)
- func EncodeJSONField(values url.Values, name string, value any, application FieldApplication) (bool, error)
- func EncodeMediaRequest(request *http.Request, index int, contracts []string, value any, ...) error
- func EncodePathParam(name string, codec ParamCodec, value ParamValue) (string, error)
- func EncodeSSEData(payload any) (string, error)
- func EncodeSSEJSONData(payload any) (string, error)
- func ErrDecodingError(svc, m string, err error) error
- func ErrEncodingError(svc, m string, err error) error
- func ErrInvalidResponse(svc, m string, code int, body string) error
- func ErrInvalidType(svc, m, expected string, actual any) error
- func ErrInvalidURL(svc, m, u string, err error) error
- func ErrRequestError(svc, m string, err error) error
- func ErrValidationError(svc, m string, err error) error
- func ErrorEncoder(encoder func(context.Context, http.ResponseWriter) Encoder, ...) func(context.Context, http.ResponseWriter, error) error
- func EscapePathRemainder(value string) string
- func EscapePathSegment(value string) string
- func FinalStatusDomain(keys []StatusSelector, selector StatusSelector, hasBody bool) []int
- func FinalizeRequestEncoding(req *http.Request, service, method string, encodeErr error) error
- func FormChildKey(prefix, name string) string
- func FormJSONValue(pairs RawPairs, name string, application FieldApplication) (jsontext.Value, bool, error)
- func FormTextUnionValue(name string, branches []FormValueBranch, closed bool) (jsontext.Value, bool, error)
- func FormTextValue(branch TextBranch) (jsontext.Value, bool, error)
- func HandleCORSPreflight(w http.ResponseWriter, r *http.Request, policy CORSPolicy, ...)
- func HeaderValues(header http.Header, name string) []string
- func MatchUntaggedText(name string, branches []TextUnionBranch, closed bool) (int, error)
- func MountDerivedHead(mux Muxer, pattern string, getHandler http.Handler)
- func MountHandler(mux Muxer, method, pattern string, handler http.Handler)
- func MultipartBinaryValue(form *MultipartForm, name string, application FieldApplication) (jsontext.Value, bool, error)
- func MultipartFieldPresent(form *MultipartForm, keys FormKeySet, siblings ParamNamespace) bool
- func MultipartJSONValue(form *MultipartForm, name string, application FieldApplication) (jsontext.Value, bool, error)
- func MultipartMetadataJSON(form *MultipartForm, name, file, header string) (jsontext.Value, bool, error)
- func NewStaticFileServer(fileSystem http.FileSystem, target string) http.Handler
- func NewUnaryHandler[Payload, Result any](spec UnaryHandlerSpec[Payload, Result]) http.Handler
- func NormalizeParamDecodeError(err error) error
- func NormalizeRequestBodyDecodeError(err error) error
- func ObserveInformational(req *http.Request, observers []InformationalObserver) (*http.Request, func(*http.Response, error) (*http.Response, error))
- func ParamValueJSON(value ParamValue, shape ParamBranchShape) (jsontext.Value, bool, error)
- func ParseFormWithLimit(req *http.Request, maxBytes int64) error
- func PrepareResponseCookie(ctx context.Context, cookie *http.Cookie) (string, error)
- func ProblemErrorFromBody(body ProblemResponse) *loom.ServiceError
- func ProblemInstanceID(instance string) string
- func ProblemInstanceURI(id string) string
- func ReadResponseBody(resp *http.Response) ([]byte, error)
- func ReadUnexpectedResponseBody(resp *http.Response) (string, error)
- func RequestBodyLimit(ctx context.Context) int64
- func RequestMetadataMiddleware(policy RequestMetadataPolicy) func(http.Handler) http.Handler
- func RequestURL(scheme, host, path string) (*url.URL, error)
- func ResolveProblemTypeAndTitle(code string, status int, explicitType, explicitTitle string) (string, string)
- func SSEEventResponse(stream *http.Response, data string) *http.Response
- func SafeDecodePayloadMessage(error) string
- func SelectMediaType(contentType string, contracts []string) (int, error)
- func SelectRequestMediaType(request *http.Request, contracts []string, optional bool) (int, error)
- func SetContentType(w http.ResponseWriter, ct string)
- func SetFormRequest(req *http.Request, body any) error
- func SetHeaderValues(header http.Header, name string, values []string) error
- func SetMultipartRequest(request *http.Request, form *MultipartForm) error
- func SetRawFormRequest(req *http.Request, encoded string) error
- func SetResponseCookie(ctx context.Context, w http.ResponseWriter, cookie *http.Cookie) error
- func ValidateResponseContract(resp *http.Response, contract ResponseContractCase) error
- func ValidateSSEResponseContract(observation *SSEResponseContractObservation, contract ResponseContractCase) error
- func ValidateWebSocketResponseContract(observation *WebSocketResponseContractObservation, ...) error
- func WithMediaFormCodec(ctx context.Context, codec MediaFormCodec) context.Context
- func WithMediaMultipartCodec(ctx context.Context, codec MediaMultipartCodec) context.Context
- func WithNonNullableBody(r *http.Request) *http.Request
- func WithNonNullableResponseBody(response *http.Response) *http.Response
- func WriteCORSActualHeaders(w http.ResponseWriter, r *http.Request, policy CORSPolicy) bool
- func WriteJSONSSEEvent(w io.Writer, msg SSEMessage, payload any) error
- func WriteMultipartForm(writer *multipart.Writer, form *MultipartForm) error
- func WriteSSEEvent(w io.Writer, msg SSEMessage) error
- type CORSOrigin
- type CORSPolicy
- type ClientError
- type ConnConfigureFunc
- type DebugDoer
- type Decoder
- type Dialer
- type Doer
- type Encoder
- type EncodingFunc
- type ErrorResponse
- type ExchangeWriter
- type FieldApplication
- type FileResponse
- type FinalKind
- type FormField
- type FormKeySet
- type FormProjection
- type FormValueBranch
- type FormValuesMarshaler
- type FormValuesUnmarshaler
- type HandlerLifecycle
- func (l *HandlerLifecycle) Context() context.Context
- func (l *HandlerLifecycle) DecodeFailed(err error, encodeError func(context.Context, http.ResponseWriter, error) error, ...)
- func (l *HandlerLifecycle) EncodeResponse(encodeResponse func(context.Context, http.ResponseWriter) error, ...) bool
- func (l *HandlerLifecycle) End()
- func (l *HandlerLifecycle) Exchange() *ExchangeWriter
- func (l *HandlerLifecycle) HandlerFailed(err error, committed bool, ...)
- func (l *HandlerLifecycle) ResponseFailed(err error, handleFailure func(context.Context, http.ResponseWriter, error))
- func (l *HandlerLifecycle) ServeFile(r *http.Request, file *FileResponse, contentType string, ...)
- func (l *HandlerLifecycle) WriteRawBody(body io.ReadCloser, ...)
- func (l *HandlerLifecycle) Writer() http.ResponseWriter
- type InformationalObserver
- type MediaFormCodec
- type MediaMultipartCodec
- type MiddlewareMuxer
- type Mounter
- type MultipartForm
- func (f *MultipartForm) AddBinary(name, media string, value any, application FieldApplication) (bool, error)
- func (f *MultipartForm) AddJSON(name, media string, value any, application FieldApplication) (bool, error)
- func (f *MultipartForm) AddParam(name, media string, codec ParamCodec, value ParamValue, ...) error
- type MultipartPart
- type MultipartPartContract
- type MultipartRequestContract
- type Muxer
- type ParamBranchShape
- type ParamCodec
- type ParamKind
- type ParamNamespace
- type ParamPair
- type ParamScalarKind
- type ParamStyle
- type ParamValue
- func DecodeCookieParam(cookies []*http.Cookie, name string, codec ParamCodec, kind ParamKind, ...) (ParamValue, error)
- func DecodeHeaderParam(name string, lines []string, present bool, codec ParamCodec, kind ParamKind) (ParamValue, error)
- func DecodeMultipartParam(form *MultipartForm, name string, codec ParamCodec, kind ParamKind, ...) (ParamValue, error)
- func DecodePairsParam(pairs RawPairs, name string, codec ParamCodec, kind ParamKind, ...) (ParamValue, error)
- func DecodePathParam(name, raw string, codec ParamCodec, kind ParamKind) (ParamValue, error)
- type ProblemResponse
- type RawPairs
- type RawPairsBuilder
- type RequestBodyPolicy
- type RequestMetadata
- type RequestMetadataPolicy
- type ResolverMuxer
- type ResponseContractCase
- type ResponseContractCaseKind
- type ResponseContractTransport
- type ResponseCookiePolicy
- type ResponseMetadata
- type ResponseNegotiationPolicy
- type RuntimeCORSPolicy
- type SSEControl
- type SSEEvent
- type SSEHandshake
- type SSEMessage
- type SSEResponseContract
- type SSEResponseContractObservation
- type SSEStreamOption
- type SSEStreamReader
- type SSEStreamWriter
- func (s *SSEStreamWriter) ClaimFailure() bool
- func (s *SSEStreamWriter) Close() error
- func (s *SSEStreamWriter) Complete(ctx context.Context, prepare func() (SSEMessage, error)) error
- func (s *SSEStreamWriter) Context() context.Context
- func (s *SSEStreamWriter) End()
- func (s *SSEStreamWriter) FinalizeSuccess(ctx context.Context) error
- func (s *SSEStreamWriter) Observation() *loomtransport.StreamObserver
- func (s *SSEStreamWriter) Open(ctx context.Context) error
- func (s *SSEStreamWriter) SendComment(ctx context.Context, text string) error
- func (s *SSEStreamWriter) SetHandshake(prepare func() (SSEHandshake, error)) error
- func (s *SSEStreamWriter) Started() bool
- func (s *SSEStreamWriter) Suppress() error
- func (s *SSEStreamWriter) WriteEvent(ctx context.Context, write func(io.Writer) error) error
- type Server
- type Servers
- type StatusCoder
- type StatusSelector
- type StatusViolationError
- type StreamWritePolicy
- type TextBranch
- type TextUnionAnnotations
- type TextUnionBranch
- type UnaryHandlerSpec
- type UnaryResult
- type Upgrader
- type WebSocketConfig
- type WebSocketLimits
- type WebSocketResponseContract
- type WebSocketResponseContractObservation
- type WebSocketStream
- func (s *WebSocketStream) Close() error
- func (s *WebSocketStream) CloseWithFinalJSON(value any) error
- func (s *WebSocketStream) CloseWithStatus(code int, reason string) error
- func (s *WebSocketStream) Conn() *websocket.Conn
- func (s *WebSocketStream) DecodeMessage(ctx context.Context, decode func([]byte) error) error
- func (s *WebSocketStream) ReadJSON(ctx context.Context, value any) error
- func (s *WebSocketStream) ReadMessage(ctx context.Context) ([]byte, error)
- func (s *WebSocketStream) RunHandler(run func() error, reportCloseError func(error)) (err error)
- func (s *WebSocketStream) SetConn(ctx context.Context, conn *websocket.Conn, cancel context.CancelFunc) error
- func (s *WebSocketStream) WriteJSON(ctx context.Context, v any) (err error)
Constants ¶
const ( // AcceptTypeKey is the context key used to store the value of the HTTP // request Accept-Type header. The value may be used by encoders and // decoders to implement a content type negotiation algorithm. AcceptTypeKey contextKey = iota + 1 // ContentTypeKey is the context key used to store the value of the HTTP // response Content-Type header when explicitly set in the DSL. The value // may be used by encoders to set the header appropriately. ContentTypeKey // LastEventIDKey is the context key used to store the Last-Event-ID // request header for Server-Sent Events endpoints. LastEventIDKey // DefaultMaxRequestBodyBytes is the default maximum number of request-body // bytes decoded by Loom's built-in HTTP decoders. DefaultMaxRequestBodyBytes = 32 << 20 // DefaultMaxErrorBodyBytes is the default maximum number of unexpected // response-body bytes included in client-side response errors. DefaultMaxErrorBodyBytes = 64 << 10 )
const ( // ResponseContractSuccess identifies a successful response contract case. ResponseContractSuccess ResponseContractCaseKind = "success" // ResponseContractError identifies an error response contract case. ResponseContractError ResponseContractCaseKind = "error" // ResponseContractInformational identifies an interim informational // response contract case. ResponseContractInformational ResponseContractCaseKind = "informational" // ResponseContractHTTP identifies an ordinary HTTP response contract. ResponseContractHTTP ResponseContractTransport = "http" // ResponseContractSSE identifies a Server-Sent Events response contract. ResponseContractSSE ResponseContractTransport = "sse" // ResponseContractWebSocket identifies a WebSocket response contract. ResponseContractWebSocket ResponseContractTransport = "websocket" )
const ( // ProblemJSONContentType is the default media type for Loom HTTP problem // responses. ProblemJSONContentType = "application/problem+json" )
Variables ¶
var ( // ErrInformationalClosed means final work has closed interim admission. ErrInformationalClosed = errors.New("loom http informational admission closed") // ErrInformationalUnsupported means the request protocol cannot carry 1xx. ErrInformationalUnsupported = errors.New("loom http informational response unsupported") // ErrInformationalLimit means the authored interim response budget is spent. ErrInformationalLimit = errors.New("loom http informational response limit exceeded") )
var ( // ErrSSEStreamClosed is returned when a control or event write is attempted // after the generated SSE stream has closed. ErrSSEStreamClosed = errors.New("loom http SSE stream closed") // ErrSSEResponseCommitted rejects metadata changes after opening or terminal admission. ErrSSEResponseCommitted = errors.New("loom http SSE response committed") // ErrInvalidSSEComment is returned when comment text contains a line break // that could inject another SSE field or event. ErrInvalidSSEComment = errors.New("loom http SSE comment contains a line break") )
var ( // ErrInvalidStreamWriteTimeout is returned when a stream write timeout is negative. ErrInvalidStreamWriteTimeout = errors.New("loom http stream write timeout must not be negative") // ErrStreamWriteDeadlineUnsupported is returned when a streaming transport // cannot install the deadline required by a write policy or caller context. ErrStreamWriteDeadlineUnsupported = errors.New("loom http stream write deadline unsupported") )
var ( // ErrInvalidRequestMetadataHeader is returned when a retained header name is invalid. ErrInvalidRequestMetadataHeader = errors.New("loom http invalid request metadata header") )
var ErrMultipartBodyAbsent = fmt.Errorf("multipart body is absent: %w", io.EOF)
ErrMultipartBodyAbsent identifies an absent multipart source. It unwraps to io.EOF for general body decoders; malformed envelopes and source failures never match this sentinel, even when their underlying error wraps io.EOF.
var ErrWebSocketBufferFull = errors.New("loom http websocket inbound buffer full")
ErrWebSocketBufferFull is returned after the inbound byte or message-count budget is exceeded. The connection closes with code 1013 and cannot recover.
var ( // ErrWebSocketStreamClosed is returned when generated code uses a stream // after its WebSocket connection has been closed. ErrWebSocketStreamClosed = errors.New("loom http websocket stream closed") )
Functions ¶
func AddRequestCookie ¶ added in v1.10.0
AddRequestCookie validates name and value using the verbatim request cookie grammar, then appends name=value to req without quoting or sanitizing it. Invalid values leave every request header unchanged. Response-only attributes and deployment policies do not apply to requests.
func AddRequestCookieParam ¶ added in v1.10.0
func AddRequestCookieParam(req *http.Request, name string, codec ParamCodec, value ParamValue, siblings ParamNamespace) error
AddRequestCookieParam validates the entire binding and its key ownership before adding verbatim cookie pairs. It leaves headers unchanged on rejection.
func AsHandlerFunc ¶ added in v1.8.0
func AsHandlerFunc(handler http.Handler) http.HandlerFunc
AsHandlerFunc adapts handler to the function type required by Muxer.
func CORSHandler ¶ added in v1.3.0
func CORSHandler(policy CORSPolicy, next http.HandlerFunc) http.HandlerFunc
CORSHandler wraps next and writes CORS response headers for matching actual browser requests. Non-CORS requests and disallowed origins pass through unchanged.
func CORSOptionsHandler ¶ added in v1.9.0
func CORSOptionsHandler(policy CORSPolicy, next http.HandlerFunc, allowedMethods []string) http.HandlerFunc
CORSOptionsHandler dispatches requests with an Access-Control-Request-Method field to CORS preflight handling and ordinary OPTIONS requests to next.
func CheckFinalStatus ¶ added in v1.10.0
func CheckFinalStatus(keys []StatusSelector, selector StatusSelector, code int, hasBody bool) error
CheckFinalStatus returns nil if code belongs to selector's final domain among keys, or a *StatusViolationError otherwise. A body-bearing response excludes 204 and 304. This check does not write headers or select a different response.
func DecodeFormValue ¶
DecodeFormValue decodes application/x-www-form-urlencoded values into target using prefix.
func DecodeFormValues ¶
DecodeFormValues decodes application/x-www-form-urlencoded values into target.
func DecodeJSONField ¶ added in v1.10.0
func DecodeJSONField(values url.Values, name string, target any, allowNull bool, application FieldApplication) (bool, error)
DecodeJSONField decodes named content using the framework JSON codec. FieldValue uses the first occurrence. FieldItems validates every occurrence as JSON and assembles one array before typed decoding; nested arrays remain single items. Absence leaves target unchanged. allowNull governs the complete value, while item null admission belongs to the target's element schema.
func DecodeMediaRequest ¶ added in v1.10.0
func DecodeMediaRequest(request *http.Request, target any, allowsNull bool, parts map[string]string, factory func(*http.Request) Decoder) error
DecodeMediaRequest invokes the supplied factory for an already selected typed branch. The branch's null contract replaces the enclosing union's null policy.
func DecodeMediaResponse ¶ added in v1.10.0
func DecodeMediaResponse(response *http.Response, target any, allowsNull bool, parts map[string]string, factory func(*http.Response) Decoder) error
DecodeMediaResponse invokes the supplied factory for a selected response branch. It preserves the response body and metadata and retains request context.
func DecodeMultipartBinary ¶ added in v1.10.0
func DecodeMultipartBinary(form *MultipartForm, name string, target any, application FieldApplication) (bool, error)
DecodeMultipartBinary decodes raw byte parts using the target's JSON byte carrier. A present empty part becomes nonnil empty bytes. Duplicate scalar parts reject.
func DecodeMultipartJSON ¶ added in v1.10.0
func DecodeMultipartJSON(form *MultipartForm, name string, target any, allowsNull bool, application FieldApplication) (bool, error)
DecodeMultipartJSON applies the framework JSON decoder to captured part content. Absence leaves target unchanged; null admission is independent of presence.
func DecodeMultipartRequestWithLimit ¶ added in v1.10.0
func DecodeMultipartRequestWithLimit(req *http.Request, maxBytes int64, decode func(*multipart.Reader) error) error
DecodeMultipartRequestWithLimit invokes decode with a multipart parser over a bounded request source. Before returning success it consumes any unread source, including epilogue, within maxBytes. A known oversized body is rejected before decode runs. Callback failures do not trigger extra reads; an observed size violation remains a request_too_large error. Request fields are unchanged and Body.Close remains caller-owned; decode must not retain the parser.
func DecodePathArray ¶ added in v1.10.0
DecodePathArray splits a raw comma-separated path capture and URL-unescapes each element exactly once. Escaped commas remain part of their element.
func DecodeResponse ¶ added in v1.10.0
func DecodeResponse(resp *http.Response, restoreBody, streamBody bool, decode func(*http.Response) (any, error)) (result any, err error)
DecodeResponse owns a response body while decode interprets its status, headers and body. It closes the original body exactly once and joins cleanup failures with decoding failures. Any failure returns a nil result.
restoreBody buffers a bounded body before decoding and restores the captured bytes afterwards, including partial bytes on read failure. streamBody marks a successful raw-body response: decode must inspect only its metadata. If decode succeeds the original body stays open and caller-owned, independently of restoreBody; if metadata validation fails it is closed.
func DefaultProblemTitle ¶ added in v1.0.9
DefaultProblemTitle returns the deterministic default problem title for code and status when no explicit title override is provided.
func DefaultProblemTypeURI ¶ added in v1.0.9
DefaultProblemTypeURI returns the deterministic default problem type URI for code when no explicit override is provided.
func DerivedHeadHandler ¶ added in v1.9.0
DerivedHeadHandler adapts an ordinary unary GET handler to HEAD. It executes the complete handler so headers, cookies, authentication, and application effects stay aligned with GET, while counting and suppressing the body. Non-upgrade informational responses are forwarded immediately with isolated headers; the final response remains buffered until the handler returns.
func EffectiveClientAddress ¶ added in v1.7.0
EffectiveClientAddress returns the trusted effective client IP when request metadata middleware has installed a snapshot. Otherwise it returns the direct network peer and never trusts forwarding headers on its own.
func EncodeFormValue ¶
EncodeFormValue appends the application/x-www-form-urlencoded representation of v to values using prefix.
func EncodeFormValues ¶
EncodeFormValues encodes v as application/x-www-form-urlencoded values.
func EncodeHeaderParam ¶ added in v1.10.0
func EncodeHeaderParam(name string, codec ParamCodec, value ParamValue) (string, error)
EncodeHeaderParam frames an admitted value as one simple header field. It rejects data that HTTP field or list framing would discard, including leading or trailing SP/HTAB in scalar values. Interior spaces and tabs remain.
func EncodeJSONField ¶ added in v1.10.0
func EncodeJSONField(values url.Values, name string, value any, application FieldApplication) (bool, error)
EncodeJSONField writes deterministic JSON using the captured application. FieldValue writes one value; FieldItems requires an array and writes one JSON document per item. Empty arrays produce no occurrences in item mode. Nil pointers, interfaces and collections are absent. Nonnil empty collections are supplied JSON values, including values with custom marshalers. JSON tags and marshalers govern the values independently of form tags. Errors publish no field occurrences, including when a custom marshaler returns a non-array.
func EncodeMediaRequest ¶ added in v1.10.0
func EncodeMediaRequest(request *http.Request, index int, contracts []string, value any, parts map[string]string, factory func(*http.Request) Encoder) error
EncodeMediaRequest publishes one selected typed representation through the supplied factory. A mapped Content-Type may refine the selection but must resolve to the same branch. Ranges require that concrete mapped value.
func EncodePathParam ¶ added in v1.10.0
func EncodePathParam(name string, codec ParamCodec, value ParamValue) (string, error)
EncodePathParam serializes one complete path segment and protects dot segments. Errors identify the binding without disclosing its value.
func EncodeSSEData ¶ added in v1.3.0
EncodeSSEData encodes a payload as an SSE data field.
func EncodeSSEJSONData ¶ added in v1.10.0
EncodeSSEJSONData encodes payload as the JSON data of a whole-event SSE frame. Unlike EncodeSSEData, strings become JSON strings and byte slices become base64 JSON strings, so every value, including empty strings, carriage returns, trailing newlines, and binary bytes, survives SSE framing and decodes to the value that was sent.
func ErrDecodingError ¶
ErrDecodingError is the error returned when the decoder fails to decode the response body.
func ErrEncodingError ¶
ErrEncodingError is the error returned when the encoder fails to encode the request body.
func ErrInvalidResponse ¶
ErrInvalidResponse is the error returned when the service responded with an unexpected response status code.
func ErrInvalidType ¶
ErrInvalidType is the error returned when the wrong type is given to a method function.
func ErrInvalidURL ¶
ErrInvalidURL is the error returned when the URL computed for an method is invalid.
func ErrRequestError ¶
ErrRequestError is the error returned when the request fails to be sent.
func ErrValidationError ¶
ErrValidationError is the error returned when the response body is properly received and decoded but fails validation.
func ErrorEncoder ¶
func ErrorEncoder(encoder func(context.Context, http.ResponseWriter) Encoder, formatter func(ctx context.Context, err error) StatusCoder) func(context.Context, http.ResponseWriter, error) error
ErrorEncoder returns an encoder that encodes errors returned by service methods. The default encoder checks whether the error is a Loom ServiceError struct and if so uses the error temporary and timeout fields to infer a proper HTTP status code and marshals the error struct to the body using the provided encoder. If the error is not a Loom ServiceError struct then it is encoded as a permanent internal server error. This behavior as well as the shape of the response can be overridden by providing a non-nil formatter.
func EscapePathRemainder ¶ added in v1.10.0
EscapePathRemainder returns value escaped as the remainder of a URL path matched by a trailing "{*name}" catch-all wildcard. It keeps the "/" separators of value and escapes each segment with EscapePathSegment, so the muxer returned by NewMuxer decodes the remainder back to value.
func EscapePathSegment ¶ added in v1.10.0
EscapePathSegment returns value escaped as one URL path segment, so that a value containing "/" or other reserved characters cannot change the route. It escapes like url.PathEscape and also escapes the dots of the "." and ".." segments, which path normalization would otherwise remove. The muxer returned by NewMuxer decodes the segment back to value. Generated path builders call it for every non-numeric path parameter.
func FinalStatusDomain ¶ added in v1.10.0
func FinalStatusDomain(keys []StatusSelector, selector StatusSelector, hasBody bool) []int
FinalStatusDomain returns a new ascending slice of final statuses selected by selector among keys. A body-bearing response excludes 204 and 304. An undeclared selector has an empty domain.
func FinalizeRequestEncoding ¶ added in v1.10.0
FinalizeRequestEncoding completes generated request preparation before the transport takes ownership of the body. It preserves a prior encoding error and closes an unpublished body on failure. A supplied Content-Length is reconciled with the final body and framing state after the encoder has run.
Explicit zero lengths require EOF before publication. The bounded-memory probe uses Request.Body's standard concurrent Read/Close contract: cancellation closes the body to unblock Read. Only a successful EOF and Close replace the body and replay function with http.NoBody. Positive streams and absent lengths retain their body and replay function unchanged.
func FormChildKey ¶
FormChildKey returns the fully qualified form key for name under prefix.
func FormJSONValue ¶ added in v1.10.0
func FormJSONValue(pairs RawPairs, name string, application FieldApplication) (jsontext.Value, bool, error)
FormJSONValue projects named JSON content without typed conversion. FieldValue uses the first occurrence; FieldItems combines every occurrence into an exact JSON array. Absence returns nil and true. Invalid JSON returns false. Null and other value predicates belong to the caller's schema.
func FormTextUnionValue ¶ added in v1.10.0
func FormTextUnionValue(name string, branches []FormValueBranch, closed bool) (jsontext.Value, bool, error)
FormTextUnionValue selects exactly one schema-only field projection. Every view runs once per call. If every view is absent the field is omitted; invalid present input, zero matches, ambiguity, and closure failure return false. Nested views preserve their own exact-one accounting without flattening. Typed decoding is deliberately excluded and remains a TextUnionBranch concern.
func FormTextValue ¶ added in v1.10.0
func FormTextValue(branch TextBranch) (jsontext.Value, bool, error)
FormTextValue projects a text field through its raw codec view and exact ParamBranchShape. Absent fields return nil, true, nil. Codec and scalar-domain mismatches return false. It never invokes Member, Evaluate, or typed Assign; schema validation belongs to the containing object or FormTextUnionValue.
func HandleCORSPreflight ¶ added in v1.3.0
func HandleCORSPreflight(w http.ResponseWriter, r *http.Request, policy CORSPolicy, allowedMethods []string)
HandleCORSPreflight writes a CORS preflight response for a matching origin. allowedMethods is the route-local method set generated for the matched path.
func HeaderValues ¶ added in v1.10.0
HeaderValues decodes a schema-based simple collection header. Repeated field lines and comma-separated items are equivalent. An absent field returns nil; a present field with no nonempty items returns a nonnil empty slice. Scalars, cookies and header-specific quoted grammars must use their own codecs.
func MatchUntaggedText ¶ added in v1.10.0
func MatchUntaggedText(name string, branches []TextUnionBranch, closed bool) (int, error)
MatchUntaggedText requires one schema and one decoder match at the same index. When closed is true, it then rejects members not evaluated by the selected schema. Presence and raw decoding belong to the callbacks and their codec owner.
func MountDerivedHead ¶ added in v1.9.0
MountDerivedHead mounts a HEAD companion for an ordinary unary GET handler. Use an explicitly designed HEAD route for files and streaming responses.
func MountHandler ¶ added in v1.8.0
MountHandler registers handler for method and pattern on mux. Generated servers use this function so handler adaptation remains runtime behavior.
func MultipartBinaryValue ¶ added in v1.10.0
func MultipartBinaryValue(form *MultipartForm, name string, application FieldApplication) (jsontext.Value, bool, error)
MultipartBinaryValue projects raw byte parts into their JSON schema spelling. One-value application rejects duplicate parts. Empty raw parts are present.
func MultipartFieldPresent ¶ added in v1.10.0
func MultipartFieldPresent(form *MultipartForm, keys FormKeySet, siblings ParamNamespace) bool
MultipartFieldPresent reports whether any physical part belongs to the captured binding, excluding sibling ownership before applying residual claims.
func MultipartJSONValue ¶ added in v1.10.0
func MultipartJSONValue(form *MultipartForm, name string, application FieldApplication) (jsontext.Value, bool, error)
MultipartJSONValue projects JSON part contents without URI decoding or typed conversion. Item application combines every part in source order into an array.
func MultipartMetadataJSON ¶ added in v1.10.0
func MultipartMetadataJSON(form *MultipartForm, name, file, header string) (jsontext.Value, bool, error)
MultipartMetadataJSON supplies a captured semantic string default from the sole uploaded file part. An explicit target part, even empty, wins. It never adds a physical part or changes closure claims. header is "filename" or "Content-Type"; duplicate source parts and absent/empty headers supply no value.
func NewStaticFileServer ¶ added in v1.9.0
func NewStaticFileServer(fileSystem http.FileSystem, target string) http.Handler
NewStaticFileServer returns a handler that serves target from fileSystem. If target is a directory, request paths select files below that directory. If target is a file, every request serves that file so wildcard routes can implement single-page application fallbacks.
func NewUnaryHandler ¶ added in v1.8.0
NewUnaryHandler creates an HTTP handler from typed endpoint adapters. It owns the request context, observation, and failure sequence.
func NormalizeParamDecodeError ¶ added in v1.10.0
NormalizeParamDecodeError reports an error raised while assigning a decoded parameter value. A server fault, such as an authored default that cannot be materialized, keeps its classification; any other error is a decode_payload error carrying err's message.
func NormalizeRequestBodyDecodeError ¶ added in v1.9.0
NormalizeRequestBodyDecodeError preserves request-too-large errors across standard-library form and multipart wrappers.
func ObserveInformational ¶ added in v1.10.0
func ObserveInformational(req *http.Request, observers []InformationalObserver) (*http.Request, func(*http.Response, error) (*http.Response, error))
ObserveInformational prepares one Do invocation and returns its finish function. Call finish exactly once with Do's response and error, before decoding. All declared selectors must be supplied, including entries with nil Observe. With no registered observers it preserves the request and finish arguments.
Observers run serially during admission. Once an observer or budget fails, later deliveries invoke no Loom observer; the caller's trace remains composed by net/http. finish retains the first Loom error, the error Do returned and any returned body's Close error. Successful bodies remain open until their normal owner closes them or reads EOF; cancellation is retained until then.
Budgets reset at GotFirstResponseByte, which native HTTP/1 and HTTP/2 deliver once per response exchange before its informational responses. A custom Doer must preserve that trace ordering. Request-write notifications do not reset budgets: HTTP/2 may deliver responses before WroteHeaders runs.
func ParamValueJSON ¶ added in v1.10.0
func ParamValueJSON(value ParamValue, shape ParamBranchShape) (jsontext.Value, bool, error)
ParamValueJSON converts a raw value into exact JSON data. False denotes an ordinary syntax/domain mismatch; errors denote invalid evaluator configuration.
func ParseFormWithLimit ¶ added in v1.9.0
ParseFormWithLimit parses req's query and URL-encoded form values while enforcing maxBytes for the request body. Unlike http.Request.ParseForm, it does not impose net/http's separate implicit 10 MiB form limit.
func PrepareResponseCookie ¶ added in v1.10.0
PrepareResponseCookie applies the active deployment policy and validates a modeled response cookie before returning its Set-Cookie field value. Policy mutations apply to cookie; failure returns no value for publication.
func ProblemErrorFromBody ¶ added in v1.0.9
func ProblemErrorFromBody(body ProblemResponse) *loom.ServiceError
ProblemErrorFromBody rebuilds a service error from a decoded public document. Properties are copied explicitly; Status never supplies missing properties. A property omitted by an authored body projection therefore remains false.
func ProblemInstanceID ¶ added in v1.0.9
ProblemInstanceID extracts the Loom error instance ID from a problem instance URI when it uses the framework default URN form.
func ProblemInstanceURI ¶ added in v1.0.9
ProblemInstanceURI returns a stable URI reference for a specific problem occurrence.
func ReadResponseBody ¶ added in v1.2.1
ReadResponseBody reads the bounded response body used when generated clients restore the response body after decoding. Read failures return any captured prefix along with the error; oversized bodies return no bytes.
func ReadUnexpectedResponseBody ¶ added in v1.2.1
ReadUnexpectedResponseBody reads the bounded body text used in generated client-side invalid-response errors.
func RequestBodyLimit ¶ added in v1.9.0
RequestBodyLimit returns the configured limit from ctx. It returns DefaultMaxRequestBodyBytes when no RequestBodyPolicy is active.
func RequestMetadataMiddleware ¶ added in v1.6.0
func RequestMetadataMiddleware(policy RequestMetadataPolicy) func(http.Handler) http.Handler
RequestMetadataMiddleware snapshots inbound request metadata before the next handler executes. Apply it with a generated server's Use method so endpoint decoders and security functions observe the same snapshot.
func RequestURL ¶ added in v1.10.0
RequestURL returns the URL of a request sent to host with scheme, whose escaped path is path, as returned by a generated path builder. The URL keeps the escaping of path, so an escaped "/" stays inside its segment. When path is not a valid escaped path, RequestURL returns the URL with path as its unescaped path and the error of unescaping it.
func ResolveProblemTypeAndTitle ¶ added in v1.0.9
func ResolveProblemTypeAndTitle(code string, status int, explicitType, explicitTitle string) (string, string)
ResolveProblemTypeAndTitle resolves the final RFC 9457 type/title pair for a problem code and HTTP status. Explicit overrides win over generated values.
func SSEEventResponse ¶ added in v1.10.0
SSEEventResponse returns an independent JSON response for one event's data. It retains the stream status for diagnostics and excludes the initiating request so event decoding does not inherit request media or nullability policy.
func SafeDecodePayloadMessage ¶ added in v1.2.1
SafeDecodePayloadMessage returns a stable client-facing description for a request body decode failure without exposing Go decoder internals.
func SelectMediaType ¶ added in v1.10.0
SelectMediaType returns the most specific matching media contract index. Missing, malformed, wildcard and unmatched Content-Type values return a service error suitable for an HTTP 415 response. Contract parameters must match; additional incoming parameters are allowed.
func SelectRequestMediaType ¶ added in v1.10.0
SelectRequestMediaType selects the request contract. An optional absent body needs no Content-Type; a nonempty body must always identify its representation.
func SetContentType ¶
func SetContentType(w http.ResponseWriter, ct string)
SetContentType initializes the response Content-Type header given a MIME type. If the Content-Type header is already set and the MIME type is "application/json" or "application/xml" then SetContentType appends a suffix to the header ("+json" or "+xml" respectively).
func SetFormRequest ¶
SetFormRequest encodes body as application/x-www-form-urlencoded and stores it in req.
func SetHeaderValues ¶ added in v1.10.0
SetHeaderValues writes a schema-based simple collection header. Nil values leave the header unchanged; nonnil empty values write an empty field. It rejects unrepresentable items before changing the header, without disclosing their text. Set-Cookie is not a comma-list field and must use the cookie APIs instead.
func SetMultipartRequest ¶ added in v1.10.0
func SetMultipartRequest(request *http.Request, form *MultipartForm) error
SetMultipartRequest publishes a complete MIME body only after encoding succeeds. A present empty part set produces an empty envelope, distinct from no body.
func SetRawFormRequest ¶ added in v1.10.0
SetRawFormRequest publishes a pre-encoded form with exact length and replay.
func SetResponseCookie ¶ added in v1.9.0
SetResponseCookie applies the active runtime policy, validates the resulting cookie, and writes it to w. Staged response metadata uses PrepareResponseCookie directly and publishes the resulting header after all metadata is valid.
func ValidateResponseContract ¶ added in v1.8.0
func ValidateResponseContract(resp *http.Response, contract ResponseContractCase) error
ValidateResponseContract validates the transport-owned wire invariants in contract against resp. The response status must belong to contract.Domain. Applications remain responsible for arranging the service state and request that produce the response.
func ValidateSSEResponseContract ¶ added in v1.8.0
func ValidateSSEResponseContract(observation *SSEResponseContractObservation, contract ResponseContractCase) error
ValidateSSEResponseContract validates an SSE handshake, observed frames, and clean end-of-stream behavior against contract.
func ValidateWebSocketResponseContract ¶ added in v1.8.0
func ValidateWebSocketResponseContract(observation *WebSocketResponseContractObservation, contract ResponseContractCase) error
ValidateWebSocketResponseContract validates a WebSocket handshake, observed server messages, and declared terminal behavior against contract.
func WithMediaFormCodec ¶ added in v1.10.0
func WithMediaFormCodec(ctx context.Context, codec MediaFormCodec) context.Context
WithMediaFormCodec supplies field codecs to the default HTTP media factories. Custom factories retain ownership of their codec choice. The callbacks belong to one encoding or decoding call and must not be reused for another carrier.
func WithMediaMultipartCodec ¶ added in v1.10.0
func WithMediaMultipartCodec(ctx context.Context, codec MediaMultipartCodec) context.Context
WithMediaMultipartCodec supplies captured part codecs to the default media factories. A custom factory retains ownership of its selected representation.
func WithNonNullableBody ¶ added in v1.10.0
WithNonNullableBody returns a shallow request copy whose built-in JSON RequestDecoder rejects a top-level null. Generated decoders use it when the DSL body is not nullable. It preserves all other decoding behavior, including absent bodies, null object fields, and non-JSON content types. Custom decoder factories remain responsible for enforcing their body contract.
func WithNonNullableResponseBody ¶ added in v1.10.0
WithNonNullableResponseBody returns a shallow response copy whose request context makes the built-in JSON ResponseDecoder reject a top-level null. Generated clients use it when the DSL response body is not nullable. The caller's response and request are unchanged; a missing request is replaced by an empty one in the copy. Custom decoder factories remain responsible for enforcing their body contract.
func WriteCORSActualHeaders ¶ added in v1.3.0
func WriteCORSActualHeaders(w http.ResponseWriter, r *http.Request, policy CORSPolicy) bool
WriteCORSActualHeaders writes CORS headers for a matching actual request.
func WriteJSONSSEEvent ¶
func WriteJSONSSEEvent(w io.Writer, msg SSEMessage, payload any) error
WriteJSONSSEEvent marshals payload as JSON and writes it as an SSE event.
func WriteMultipartForm ¶ added in v1.10.0
func WriteMultipartForm(writer *multipart.Writer, form *MultipartForm) error
WriteMultipartForm writes the retained ordered part set and closes its MIME envelope. Content labels and raw bytes are supplied by captured field codecs.
func WriteSSEEvent ¶
func WriteSSEEvent(w io.Writer, msg SSEMessage) error
WriteSSEEvent writes a single SSE event frame.
Types ¶
type CORSOrigin ¶ added in v1.3.0
type CORSOrigin struct {
Pattern string
Regex bool
Methods []string
Headers []string
Expose []string
MaxAge int
Credentials bool
}
CORSOrigin defines one allowed origin and the response policy attached to it. Pattern is an exact origin, "*", or a regular expression when Regex is true.
type CORSPolicy ¶ added in v1.3.0
type CORSPolicy struct {
Origins []CORSOrigin
}
CORSPolicy defines the Cross-Origin Resource Sharing headers generated handlers may write for actual and preflight requests.
type ClientError ¶
type ClientError struct {
// Name is a name for this class of errors.
Name string
// Message contains the specific error details.
Message string
// Service is the name of the service.
Service string
// Method is the name of the service method.
Method string
// Is the error temporary?
Temporary bool
// Is the error a timeout?
Timeout bool
// Is the error a server-side fault?
Fault bool
// The original error if any
Err error
}
ClientError is an error returned by a HTTP service client.
func (ClientError) Unwrap ¶
func (c ClientError) Unwrap() error
type ConnConfigureFunc ¶
ConnConfigureFunc is used to configure a websocket connection with custom handlers. The cancel function cancels the request context when invoked in the configure function. The framing limit is installed before this hook runs. A hook that returns a different connection owns releasing the input without invalidating the returned connection. The stream owns the returned connection; its expanded-message limit still applies. A nil result is terminal: the stream records and closes the input connection.
type DebugDoer ¶
type DebugDoer interface {
Doer
// Fprint prints the latest exchange snapshot without reading its response body.
// Output is best effort; incomplete captures are identified in the output.
Fprint(io.Writer)
}
DebugDoer is a Doer that can print the low level HTTP details.
func NewDebugDoer ¶
func NewDebugDoer(d Doer, fields ...diagnostics.Fields) DebugDoer
NewDebugDoer wraps d with bounded, redacted development diagnostics. Response bodies are observed only as the caller reads them, with original errors and Close behavior preserved. The exchange prints once to stderr at observed EOF or caller Close; nil/http.NoBody responses print immediately. Unread, unclosed responses do not print automatically. Request capture retains its bounded prefix/GetBody behavior. Authored wire credential fields are copied when the wrapper is constructed; conventional credential names are always masked. Concurrent Do calls are not supported.
type Decoder ¶
Decoder provides the actual decoding algorithm used to load HTTP request and response bodies.
func RequestDecoder ¶
RequestDecoder returns a HTTP request body decoder suitable for the given request. The decoder handles the following mime types:
- application/json and valid structured +json media using package encoding/json/v2
- application/xml using package encoding/xml
- application/gob using package encoding/gob
- text/html and text/plain for strings
RequestDecoder defaults to JSON when Content-Type is missing and rejects unsupported media types.
func ResponseDecoder ¶
ResponseDecoder returns a HTTP response decoder. The decoder handles the following content types:
- application/json using package encoding/json/v2 (default)
- application/xml using package encoding/xml
- application/gob using package encoding/gob
- text/html and text/plain for strings
JSON decoding rejects a top-level null for responses returned by WithNonNullableResponseBody.
type Dialer ¶
type Dialer interface {
// DialContext creates a client connection to the websocket server.
DialContext(ctx context.Context, url string, h http.Header) (*websocket.Conn, *http.Response, error)
}
Dialer creates a websocket connection to a given URL.
type Encoder ¶
Encoder provides the actual encoding algorithm used to write HTTP request and response bodies.
func MediaResponseEncoder ¶ added in v1.10.0
func MediaResponseEncoder(ctx context.Context, writer http.ResponseWriter, index int, contracts []string, value any, parts map[string]string, factory func(context.Context, http.ResponseWriter) Encoder) (Encoder, error)
MediaResponseEncoder selects a response representation before status commitment. Its returned encoder writes the selected value and ignores its Encode argument. The service chooses the variant; this function does not negotiate Accept.
func RequestEncoder ¶
RequestEncoder returns a HTTP request encoder. The encoder uses package encoding/json/v2.
func ResponseEncoder ¶
func ResponseEncoder(ctx context.Context, w http.ResponseWriter) Encoder
ResponseEncoder returns a HTTP response encoder leveraging the mime type set in the context under the AcceptTypeKey or the ContentTypeKey if any. The encoder supports the following mime types:
- application/json using package encoding/json/v2
- application/xml using package encoding/xml
- application/gob using package encoding/gob
- text/html and text/plain for strings
ResponseEncoder defaults to the JSON encoder if the context AcceptTypeKey or ContentTypeKey value does not match any of the supported mime types or is missing altogether. Responses selected through Accept include Vary: Accept, including JSON fallbacks. Explicit ContentTypeKey overrides do not add it.
type EncodingFunc ¶
EncodingFunc allows a function with appropriate signature to act as a Decoder/Encoder.
func (EncodingFunc) Decode ¶
func (f EncodingFunc) Decode(v any) error
Decode implements the Decoder interface. It simply calls f(v).
func (EncodingFunc) Encode ¶
func (f EncodingFunc) Encode(v any) error
Encode implements the Encoder interface. It simply calls f(v).
type ErrorResponse ¶
type ErrorResponse = ProblemResponse
ErrorResponse is kept as an alias for compatibility with older Loom code.
type ExchangeWriter ¶ added in v1.10.0
type ExchangeWriter struct {
// contains filtered or unexported fields
}
ExchangeWriter serializes authored informational responses with final admission for one HTTP request. Obtain it from HandlerLifecycle or its context; its zero value is not an initialized exchange.
func ExchangeFromContext ¶ added in v1.10.0
func ExchangeFromContext(ctx context.Context) *ExchangeWriter
ExchangeFromContext returns the request's shared informational writer, or nil when ctx was not obtained from a HandlerLifecycle.
func (*ExchangeWriter) BeginFinal ¶ added in v1.10.0
func (e *ExchangeWriter) BeginFinal(_ FinalKind)
BeginFinal permanently closes informational admission before final headers are read or prepared. It waits for an admitted Send, is idempotent and performs no I/O or observation callback. kind documents the calling path only: repeated kinds do not change behavior. Physical commit and precommit fallback remain owned by the existing captured response writer and handler lifecycle.
func (*ExchangeWriter) Send ¶ added in v1.10.0
func (e *ExchangeWriter) Send(code int, headers http.Header) error
Send publishes one authored informational response with exactly headers, then restores the final response header map. Only statuses 102 through 199 are permitted; generated emitters separately validate their declared domains and header constraints. Callers must not mutate headers during Send.
type FieldApplication ¶ added in v1.10.0
type FieldApplication uint8
FieldApplication identifies the value encoded by a named content field.
const ( // FieldValue encodes one complete value in one field occurrence. FieldValue FieldApplication = iota // FieldItems encodes each top-level array item as a separate field occurrence. FieldItems )
type FileResponse ¶ added in v1.8.0
type FileResponse struct {
// Name is the content name used to infer its media type.
Name string
// ModTime is the content modification time. A zero value omits Last-Modified.
ModTime time.Time
// Content is the seekable content served in the response.
Content io.ReadSeeker
}
FileResponse describes seekable file or media content returned by a service method. Name is used to infer Content-Type, and a non-zero ModTime enables Last-Modified and conditional request handling. Content must support seeking so the standard library can serve byte ranges.
func (*FileResponse) ServeHTTP ¶ added in v1.8.0
func (f *FileResponse) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP serves the file response using net/http ServeContent semantics. Callers must set application response headers before calling ServeHTTP.
type FinalKind ¶ added in v1.10.0
type FinalKind uint8
FinalKind identifies the caller beginning final response work. It does not imply physical commitment or successful publication.
const ( // FinalResult marks result encoding, or handler-end admission cleanup. FinalResult FinalKind = iota // FinalError marks error routing or encoding. FinalError // FinalSSEOpen marks the first SSE handshake preparation. FinalSSEOpen // FinalUpgrade marks WebSocket upgrade preparation. FinalUpgrade // FinalFile marks file response preparation. FinalFile // FinalRaw marks raw response preparation, before any body peek. FinalRaw // FinalRedirect marks redirect header preparation. FinalRedirect // MaxInformationalResponses bounds authored interim responses per exchange. // The transport's automatic 100 Continue has an independent budget. MaxInformationalResponses = 8 )
type FormField ¶ added in v1.10.0
type FormField struct {
// Name is the effective form-root property name, not a nested JSON tag.
Name string
// Keys retains the full field namespace, including all union alternatives.
Keys FormKeySet
// View returns exact JSON and true for a present value, nil and true for
// absence, or false for a codec/schema mismatch. Explicit null is nonnil
// JSON. Errors identify invalid evaluator configuration or evaluator failure.
View func() (jsontext.Value, bool, error)
}
FormField projects one declared form property into the logical root object. Construct fresh views for each input and keep their raw carrier immutable.
type FormKeySet ¶ added in v1.10.0
type FormKeySet struct {
// Literals contains exact decoded form keys.
Literals []string
// Prefixes contains deepObject names, each claiming name[key].
Prefixes []string
// Residual claims keys not explicitly owned by another field.
Residual bool
}
FormKeySet describes one field's complete captured physical key ownership. Union fields include every alternative, independently of selection.
type FormProjection ¶ added in v1.10.0
type FormProjection struct {
// Value contains declared logical properties and their exact JSON values.
// Unknown physical fields are never inserted into this JSON object.
Value jsontext.Value
// Members contains the distinct decoded physical keys in the body.
Members []string
// Unclaimed contains physical keys outside all captured field claims.
Unclaimed []string
// FieldClaims maps logical properties to their present physical keys.
// A union field retains keys owned by every alternative.
FieldClaims map[string][]string
}
FormProjection keeps logical schema values separate from physical keys. Construct it through FormObjectJSON or FormMapJSON and keep it immutable while evaluating branch membership and closure annotations.
func FormMapJSON ¶ added in v1.10.0
func FormMapJSON(pairs RawPairs, value func(string) (jsontext.Value, bool, error)) (FormProjection, bool, error)
FormMapJSON projects a present form body into a map using its captured value codec. value runs once per distinct decoded raw key, including the empty key; its captured RawPairs retain all repetitions for the codec to interpret. It may project text, JSON, collections or nested unions, but a key present in the body must produce a nonnil value. Empty bodies project {}. The callback uses FormField.View's mismatch/error contract. No typed Go conversion occurs. Physical members and claims are captured before callbacks and retained on a value mismatch, with nil Value, for independent typed-domain evaluation.
func FormObjectJSON ¶ added in v1.10.0
func FormObjectJSON(pairs RawPairs, fields []FormField) (FormProjection, bool, error)
FormObjectJSON projects a present form body into one branch's logical object. Empty input produces {}. The media owner decides optional body absence before calling it. Logical values and physical ownership stay separate: an unknown key may equal an exploded property's logical name without replacing its value. Static descriptors are validated before any input-dependent callback runs. False denotes an input mismatch; errors denote invalid configuration or evaluator failure. Unknown values are ignored; invalid UTF-8 names reject. On a field mismatch, Value is nil but complete physical ownership is retained so an independent typed decoder can apply the same branch closure policy.
func MultipartObjectJSON ¶ added in v1.10.0
func MultipartObjectJSON(form *MultipartForm, fields []FormField) (FormProjection, bool, error)
MultipartObjectJSON projects one object alternative while retaining original physical part claims. Each view supplies its independently decoded value.
func (FormProjection) Annotations ¶ added in v1.10.0
func (p FormProjection) Annotations(evaluate func(jsontext.Value) ([]string, error), evaluateUnknown bool) (TextUnionAnnotations, error)
Annotations maps evaluated logical properties to physical form key claims. evaluateUnknown is the captured explicit-open policy (additionalProperties: true), not the implicit openness default. Only explicit open schemas evaluate unclaimed fields. Both returned sets contain physical decoded member names.
func (FormProjection) Schema ¶ added in v1.10.0
func (p FormProjection) Schema(member func(jsontext.Value) (bool, error), closed bool) (bool, error)
Schema checks logical membership and the branch's captured object closure. It invokes member before input-dependent closure rejection so evaluator configuration failures cannot be hidden by an unknown physical key. Outer union closure belongs to MatchUntaggedText after original branch counting.
type FormValueBranch ¶ added in v1.10.0
type FormValueBranch struct {
// View has the same presence and mismatch contract as FormField.View.
View func() (jsontext.Value, bool, error)
// Member checks the exact projected JSON without Go carrier restrictions.
Member func(jsontext.Value) (bool, error)
// Evaluate reports evaluated object members after this schema matches.
// Closed unions require it when the selected value is an object.
Evaluate func(jsontext.Value) ([]string, error)
}
FormValueBranch supplies one schema-only projection of a form field. Views may recursively call FormTextUnionValue; typed conversion is separate.
type FormValuesMarshaler ¶
type FormValuesMarshaler interface {
// MarshalFormValues appends the encoded representation of the receiver to
// the given values using the given field prefix.
MarshalFormValues(values url.Values, prefix string) error
}
FormValuesMarshaler is implemented by generated types that need custom application/x-www-form-urlencoded encoding semantics.
type FormValuesUnmarshaler ¶
type FormValuesUnmarshaler interface {
// UnmarshalFormValues decodes the receiver from the given values using the
// given field prefix.
UnmarshalFormValues(values url.Values, prefix string) error
}
FormValuesUnmarshaler is implemented by generated types that need custom application/x-www-form-urlencoded decoding semantics.
type HandlerLifecycle ¶ added in v1.8.0
type HandlerLifecycle struct {
// contains filtered or unexported fields
}
HandlerLifecycle owns the shared context, observation, and failure routing for one generated HTTP handler invocation.
func NewHandlerLifecycle ¶ added in v1.8.0
func NewHandlerLifecycle( w http.ResponseWriter, r *http.Request, service string, method string, ) *HandlerLifecycle
NewHandlerLifecycle starts the shared runtime lifecycle for a generated HTTP handler invocation.
func (*HandlerLifecycle) Context ¶ added in v1.8.0
func (l *HandlerLifecycle) Context() context.Context
Context returns the request context enriched with Loom transport metadata.
func (*HandlerLifecycle) DecodeFailed ¶ added in v1.8.0
func (l *HandlerLifecycle) DecodeFailed( err error, encodeError func(context.Context, http.ResponseWriter, error) error, handleFailure func(context.Context, http.ResponseWriter, error), )
DecodeFailed records and writes a request decoding failure.
func (*HandlerLifecycle) EncodeResponse ¶ added in v1.9.0
func (l *HandlerLifecycle) EncodeResponse( encodeResponse func(context.Context, http.ResponseWriter) error, encodeError func(context.Context, http.ResponseWriter, error) error, handleFailure func(context.Context, http.ResponseWriter, error), ) bool
EncodeResponse writes response metadata or a buffered response body. When encoding fails before commit, it restores the original headers and encodes the failure through the generated error formatter. It reports whether the response encoding succeeded.
func (*HandlerLifecycle) End ¶ added in v1.8.0
func (l *HandlerLifecycle) End()
End closes informational admission and completes request observation while preserving panic propagation. It does not commit a response or publish success.
func (*HandlerLifecycle) Exchange ¶ added in v1.10.0
func (l *HandlerLifecycle) Exchange() *ExchangeWriter
Exchange returns the single exchange writer associated with this lifecycle.
func (*HandlerLifecycle) HandlerFailed ¶ added in v1.8.0
func (l *HandlerLifecycle) HandlerFailed( err error, committed bool, encodeError func(context.Context, http.ResponseWriter, error) error, handleFailure func(context.Context, http.ResponseWriter, error), )
HandlerFailed records an endpoint failure. When committed is true, the transport can no longer encode an HTTP error response and the failure is routed directly to handleFailure.
func (*HandlerLifecycle) ResponseFailed ¶ added in v1.8.0
func (l *HandlerLifecycle) ResponseFailed( err error, handleFailure func(context.Context, http.ResponseWriter, error), )
ResponseFailed records a response write or close failure and routes it to handleFailure.
func (*HandlerLifecycle) ServeFile ¶ added in v1.8.0
func (l *HandlerLifecycle) ServeFile( r *http.Request, file *FileResponse, contentType string, encodeResponse func(context.Context, http.ResponseWriter) error, encodeError func(context.Context, http.ResponseWriter, error) error, handleFailure func(context.Context, http.ResponseWriter, error), )
ServeFile encodes response metadata, applies the designed content type, serves file with standard HTTP semantics, and closes seekable content when it also implements io.Closer.
func (*HandlerLifecycle) WriteRawBody ¶ added in v1.8.0
func (l *HandlerLifecycle) WriteRawBody( body io.ReadCloser, encodeResponse func(context.Context, http.ResponseWriter) error, encodeError func(context.Context, http.ResponseWriter, error) error, handleFailure func(context.Context, http.ResponseWriter, error), )
WriteRawBody encodes response metadata, streams body, closes it, and applies the generated HTTP late-error policy.
func (*HandlerLifecycle) Writer ¶ added in v1.8.0
func (l *HandlerLifecycle) Writer() http.ResponseWriter
Writer returns the response writer wrapped for transport observation.
type InformationalObserver ¶ added in v1.10.0
type InformationalObserver struct {
// Selector is the declared informational response key.
Selector StatusSelector
// Observe synchronously decodes and observes a selected response. Headers
// are read-only during this call. A nonnil error aborts this Do invocation.
// A nil function leaves this selector declared but unobserved.
Observe func(context.Context, int, http.Header) error
}
InformationalObserver binds a declared informational selector to an optional observer. Keep declarations with no registered observer in the slice too.
type MediaFormCodec ¶ added in v1.10.0
type MediaFormCodec struct {
// Encode returns the complete form bytes, preserving structural delimiters.
Encode func() (string, error)
// Decode consumes raw pairs and ordinary decoded values from the same body.
Decode func(RawPairs, map[string][]string) error
}
MediaFormCodec binds generated typed form fields to one selected media occurrence. Encode and Decode capture that occurrence's concrete carrier; only the callback for the current direction needs to be supplied.
type MediaMultipartCodec ¶ added in v1.10.0
type MediaMultipartCodec struct {
// Encode returns the complete validated part set before publication.
Encode func() (*MultipartForm, error)
// Decode consumes an immutable once-parsed part set within the body limit.
Decode func(*MultipartForm) error
}
MediaMultipartCodec binds one captured multipart occurrence to its concrete generated carrier. Callbacks belong to one exchange and one direction.
type MiddlewareMuxer ¶
type MiddlewareMuxer interface {
Muxer
// Use appends a middleware to the list of middlewares to be applied
// to the Muxer. Use must be called before Handle or before mounting a
// generated server.
Use(func(http.Handler) http.Handler)
}
MiddlewareMuxer makes it possible to mount middlewares downstream of the Muxer.
type Mounter ¶
type Mounter interface {
Mount(Muxer)
}
Mounter is the interface for servers that allow mounting their endpoints into a muxer.
type MultipartForm ¶
type MultipartForm struct {
// Parts retains every physical part in source order, including empty names and files.
Parts []MultipartPart
}
MultipartForm is the parsed in-memory representation of a multipart request body.
func ReadMultipartForm ¶
func ReadMultipartForm(req *http.Request) (*MultipartForm, error)
ReadMultipartForm reads the request's multipart body using RequestBodyLimit. The complete encoded body counts toward the limit, including headers, boundaries and epilogue. The caller retains ownership of Body.Close.
func ReadMultipartFormWithLimit ¶ added in v1.9.0
func ReadMultipartFormWithLimit(req *http.Request, maxBytes int64) (*MultipartForm, error)
ReadMultipartFormWithLimit reads a complete multipart request within maxBytes encoded source bytes. It returns no form on decoding or completion failure. The request must not already have been parsed; the caller owns Body.Close.
func (*MultipartForm) AddBinary ¶ added in v1.10.0
func (f *MultipartForm) AddBinary(name, media string, value any, application FieldApplication) (bool, error)
AddBinary appends raw byte parts without base64 conversion. Item application removes exactly one array level. Nil carriers are absent; empty bytes are present.
func (*MultipartForm) AddJSON ¶ added in v1.10.0
func (f *MultipartForm) AddJSON(name, media string, value any, application FieldApplication) (bool, error)
AddJSON appends complete JSON parts with the captured media label and application. Encoding is atomic; failures leave the existing part set unchanged.
func (*MultipartForm) AddParam ¶ added in v1.10.0
func (f *MultipartForm) AddParam(name, media string, codec ParamCodec, value ParamValue, siblings ParamNamespace) error
AddParam appends one styled binding atomically. Data that collides with a literal collection delimiter is unspellable and rejected before publication.
type MultipartPart ¶ added in v1.10.0
type MultipartPart struct {
// Name is the literal Content-Disposition form name.
Name string
// Filename is the optional uploaded filename.
Filename string
// ContentType is the part media label.
ContentType string
// Data contains the complete raw part payload.
Data []byte
}
MultipartPart retains a physical part and its uninterpreted payload.
type MultipartPartContract ¶ added in v1.8.0
type MultipartPartContract struct {
// Name is the multipart form field name.
Name string
// MediaType is the default media type for the part value.
MediaType string
// Required reports whether the request body requires the part.
Required bool
}
MultipartPartContract describes one designed multipart request field.
type MultipartRequestContract ¶ added in v1.8.0
type MultipartRequestContract struct {
// ContentType is the request media type.
ContentType string
// Parts lists the designed multipart fields in body order.
Parts []MultipartPartContract
}
MultipartRequestContract describes the stable request shape supplied to a consumer-owned multipart response scenario.
type Muxer ¶
type Muxer interface {
// Handle registers the handler function for the given method
// and pattern.
Handle(method, pattern string, handler http.HandlerFunc)
// ServeHTTP dispatches the request to the handler whose method
// matches the request method and whose pattern most closely
// matches the request URL.
ServeHTTP(http.ResponseWriter, *http.Request)
// Vars returns the path variables captured for the given
// request after URL path unescaping.
Vars(*http.Request) map[string]string
// RawVars returns the path variables captured for the given request
// with their URL path escaping preserved.
RawVars(*http.Request) map[string]string
}
Muxer is the HTTP request multiplexer interface used by the generated code. ServeHTTP must match the HTTP method and URL of each incoming request against the list of registered patterns and call the handler for the corresponding method and the pattern that most closely matches the URL.
The patterns may include wildcards that identify URL segments that must be captured.
There are two forms of wildcards the implementation must support:
"{name}" wildcards capture a single path segment, for example the pattern "/images/{name}" captures "/images/favicon.ico" and adds the key "name" with the value "favicon.ico" to the map returned by Vars.
"{*name}" wildcards must appear at the end of the pattern and captures the entire path starting where the wildcard matches. For example the pattern "/images/{*filename}" captures "/images/public/thumbnail.jpg" and associates the key key "filename" with "public/thumbnail.jpg" in the map returned by Vars.
The names of wildcards must match the regular expression "[a-zA-Z0-9_]+". A pattern has at most one catch-all, and "*" may appear only inside a trailing "/{*name}"; regular expression parameters are not supported.
type ParamBranchShape ¶ added in v1.10.0
type ParamBranchShape struct {
// Kind selects a scalar, sequential or associative carrier.
Kind ParamKind
// Element describes a scalar or sequence element.
Element ParamScalarKind
// Properties describes a fixed associative carrier; nil denotes a map.
Properties map[string]ParamScalarKind
// MapValue describes each dynamic associative value.
MapValue ParamScalarKind
}
ParamBranchShape describes conversion from raw text to the JSON data model.
type ParamCodec ¶ added in v1.10.0
type ParamCodec struct {
// Style selects the wire grammar.
Style ParamStyle
// Explode selects the expanded spelling for collections.
Explode bool
}
ParamCodec is a resolved style and explode setting.
type ParamKind ¶ added in v1.10.0
type ParamKind uint8
ParamKind distinguishes scalar, sequential and associative raw values.
type ParamNamespace ¶ added in v1.10.0
type ParamNamespace struct {
// Literals contains exact decoded keys owned by siblings.
Literals []string
// Prefixes contains sibling deepObject names, each claiming name[key].
Prefixes []string
// OwnedLiterals limits a fixed binding to these decoded wire keys. Nil
// permits dynamic ownership; a nonnil empty list owns no keys.
OwnedLiterals []string
}
ParamNamespace identifies sibling claims and an optional binding allowlist.
type ParamPair ¶ added in v1.10.0
type ParamPair struct {
// Key is the decoded member name.
Key string
// Value is the decoded member text.
Value string
}
ParamPair is one decoded associative entry.
type ParamScalarKind ¶ added in v1.10.0
type ParamScalarKind uint8
ParamScalarKind identifies a raw scalar's JSON domain without Go widths.
const ( // ParamBoolean accepts JSON boolean text. ParamBoolean ParamScalarKind = iota // ParamInteger accepts JSON integers without a carrier-width limit. ParamInteger // ParamNumber accepts exact JSON number tokens. ParamNumber // ParamString treats raw text as a JSON string. ParamString // ParamBytes projects raw byte text to its canonical JSON byte string for // schema predicates. The location codec still sends and receives raw text. ParamBytes )
type ParamStyle ¶ added in v1.10.0
type ParamStyle uint8
ParamStyle selects an OpenAPI parameter wire grammar.
const ( // ParamSimple uses simple list or associative expansion. ParamSimple ParamStyle = iota // ParamMatrix uses named semicolon-prefixed path expansion. ParamMatrix // ParamLabel uses dot-prefixed path expansion. ParamLabel // ParamForm uses form-style URI expansion. ParamForm // ParamSpaceDelimited separates members with encoded spaces. ParamSpaceDelimited // ParamPipeDelimited separates members with encoded vertical bars. ParamPipeDelimited // ParamDeepObject carries entries in bracketed keys. ParamDeepObject // ParamCookie uses verbatim cookie pairs. ParamCookie )
type ParamValue ¶ added in v1.10.0
type ParamValue struct {
// Kind selects Text, Items or Pairs.
Kind ParamKind
// Present distinguishes absent bindings from supplied empty values.
Present bool
// Text contains a scalar value.
Text string
// Items contains ordered sequence elements.
Items []string
// Pairs contains associative entries in received or authored order.
Pairs []ParamPair
}
ParamValue preserves raw text and presence before typed conversion.
func DecodeCookieParam ¶ added in v1.10.0
func DecodeCookieParam(cookies []*http.Cookie, name string, codec ParamCodec, kind ParamKind, siblings ParamNamespace) (ParamValue, error)
DecodeCookieParam decodes cookie pairs, retaining all occurrences for exploded sequences and the first occurrence for each scalar or associative name.
func DecodeHeaderParam ¶ added in v1.10.0
func DecodeHeaderParam(name string, lines []string, present bool, codec ParamCodec, kind ParamKind) (ParamValue, error)
DecodeHeaderParam combines physical lines using HTTP simple-list framing.
func DecodeMultipartParam ¶ added in v1.10.0
func DecodeMultipartParam(form *MultipartForm, name string, codec ParamCodec, kind ParamKind, siblings ParamNamespace) (ParamValue, error)
DecodeMultipartParam reads a captured style grammar from literal part values. Unlike URL form fields, multipart names and values undergo no URI decoding.
func DecodePairsParam ¶ added in v1.10.0
func DecodePairsParam(pairs RawPairs, name string, codec ParamCodec, kind ParamKind, siblings ParamNamespace) (ParamValue, error)
DecodePairsParam reads the binding's owned keys using its resolved grammar. Unknown fixed-object keys and sibling keys are ignored before value parsing.
func DecodePathParam ¶ added in v1.10.0
func DecodePathParam(name, raw string, codec ParamCodec, kind ParamKind) (ParamValue, error)
DecodePathParam reads a raw path capture, splitting before percent decoding. Complete protected dot segments are restored before processing the style.
type ProblemResponse ¶ added in v1.0.9
type ProblemResponse struct {
// Type identifies the problem category with a URI reference.
Type string `json:"type" xml:"type" form:"type"`
// Title summarizes the problem category.
Title string `json:"title" xml:"title" form:"title"`
// Status is the response status selected by the transport.
Status int `json:"status" xml:"status" form:"status"`
// Detail is the safe explanation of this occurrence.
Detail string `json:"detail" xml:"detail" form:"detail"`
// Instance identifies this occurrence with a URI reference.
Instance string `json:"instance" xml:"instance" form:"instance"`
// Code is the service error's stable machine-readable name.
Code string `json:"code" xml:"code" form:"code"`
// Timeout reports the source error's timeout property, independently of Status.
Timeout bool `json:"timeout" xml:"timeout" form:"timeout"`
// Temporary reports whether the source error is transient, independently of Status.
Temporary bool `json:"temporary" xml:"temporary" form:"temporary"`
// Fault reports the source error's server-fault property, independently of Status.
Fault bool `json:"fault" xml:"fault" form:"fault"`
// RetryHint optionally describes how to correct or retry the operation.
RetryHint *string `json:"retry_hint,omitempty" xml:"retry_hint,omitempty" form:"retry_hint,omitempty"`
}
ProblemResponse is the default RFC 9457 problem document encoded in HTTP responses for Loom service errors.
func NewProblemResponse ¶ added in v1.0.9
func NewProblemResponse(_ context.Context, err error, status int, problemType, problemTitle string) *ProblemResponse
NewProblemResponse creates a problem document from err using the supplied status and optional explicit type/title overrides.
func (*ProblemResponse) StatusCode ¶ added in v1.0.9
func (resp *ProblemResponse) StatusCode() int
StatusCode returns the HTTP status code carried by the problem document.
type RawPairs ¶ added in v1.10.0
type RawPairs struct {
// contains filtered or unexported fields
}
RawPairs retains query or form pairs before value percent decoding.
func ParseRawFormWithLimit ¶ added in v1.10.0
ParseRawFormWithLimit reads the form body once under maxBytes and initializes PostForm from the same bytes, preserving raw delimiters for styled fields. The returned carrier also retains whether any body bytes were read, including nonempty input that decodes to no fields.
func ParseRawPairs ¶ added in v1.10.0
ParseRawPairs validates raw query/form syntax while retaining value escapes.
func RawPairsFromValue ¶ added in v1.10.0
RawPairsFromValue retains one already bounded query/form parameter value. name is decoded; rawValue retains percent escapes and collection delimiters. Ampersands and semicolons are data, because the caller has already separated this value from other parameters. Invalid percent escapes are rejected.
func (RawPairs) HasInput ¶ added in v1.10.0
HasInput reports whether the carrier was parsed from nonempty input. It is independent of its decoded key count: "&&" has input but no pairs. Form body owners use this fact to distinguish an absent optional body from a supplied empty value set. Named parameter presence still comes from its owned keys.
type RawPairsBuilder ¶ added in v1.10.0
type RawPairsBuilder struct {
// contains filtered or unexported fields
}
RawPairsBuilder assembles styled fields alongside ordinary URL values.
func (*RawPairsBuilder) Add ¶ added in v1.10.0
func (b *RawPairsBuilder) Add(name string, codec ParamCodec, value ParamValue, siblings ParamNamespace) error
Add validates and appends one binding atomically, rejecting sibling key claims.
type RequestBodyPolicy ¶ added in v1.9.0
type RequestBodyPolicy struct {
// contains filtered or unexported fields
}
RequestBodyPolicy is an immutable request-body size policy. Its Handler method applies the limit before generated or application code reads the request body.
func NewRequestBodyPolicy ¶ added in v1.9.0
func NewRequestBodyPolicy(maxBytes int64) (RequestBodyPolicy, error)
NewRequestBodyPolicy validates maxBytes and returns an immutable request-body policy. maxBytes must be positive.
func (RequestBodyPolicy) Handler ¶ added in v1.9.0
func (p RequestBodyPolicy) Handler(next http.Handler) http.Handler
Handler wraps next with the request-body limit. Generated JSON, text, form, and multipart decoders preserve an exceeded limit as Loom's standard 413 service error. Raw-body services receive the same error when reading Body. Handler panics when p was not constructed by NewRequestBodyPolicy.
func (RequestBodyPolicy) MaxBytes ¶ added in v1.9.0
func (p RequestBodyPolicy) MaxBytes() int64
MaxBytes returns the largest request body accepted by the policy.
type RequestMetadata ¶ added in v1.6.0
type RequestMetadata struct {
// Method is the request method.
Method string
// Path is the decoded request URL path.
Path string
// Host is the effective host after trusted-proxy processing.
Host string
// Scheme is the effective http or https scheme after trusted-proxy processing.
Scheme string
// ClientAddr is the effective client IP after trusted-proxy processing.
ClientAddr string
// PeerAddr is the direct network peer IP and is never forwarded.
PeerAddr string
// RequestID is the X-Request-Id header value.
RequestID string
// UserAgent is the request User-Agent value.
UserAgent string
// Origin is the request Origin value.
Origin string
// SecFetchSite is the request Sec-Fetch-Site value.
SecFetchSite string
// contains filtered or unexported fields
}
RequestMetadata is an immutable snapshot of an inbound HTTP request.
func RequestMetadataFromContext ¶ added in v1.6.0
func RequestMetadataFromContext(ctx context.Context) (RequestMetadata, bool)
RequestMetadataFromContext returns the inbound request metadata snapshot.
func (RequestMetadata) HeaderValues ¶ added in v1.6.0
func (m RequestMetadata) HeaderValues(name string) []string
HeaderValues returns a copy of the retained values for name.
func (RequestMetadata) Headers ¶ added in v1.6.0
func (m RequestMetadata) Headers() http.Header
Headers returns a fresh clone of all explicitly retained headers.
type RequestMetadataPolicy ¶ added in v1.6.0
type RequestMetadataPolicy struct {
// contains filtered or unexported fields
}
RequestMetadataPolicy is an immutable trusted-proxy and retained-header policy.
func NewRequestMetadataPolicy ¶ added in v1.6.0
func NewRequestMetadataPolicy( retainedHeaders []string, trustedProxies []netip.Prefix, ) (RequestMetadataPolicy, error)
NewRequestMetadataPolicy validates and returns an immutable metadata policy. retainedHeaders is an explicit allowlist; Authorization and Cookie are not retained unless named. trustedProxies contains direct peer CIDR ranges that may supply X-Forwarded-For, X-Forwarded-Host, and X-Forwarded-Proto. Host and scheme use the final value across all repeated header lines.
type ResolverMuxer ¶
type ResolverMuxer interface {
MiddlewareMuxer
ResolvePattern(*http.Request) string
}
ResolverMuxer is a MiddlewareMuxer that can resolve the route pattern used to register the handler for the given request.
func NewMuxer ¶
func NewMuxer() ResolverMuxer
NewMuxer returns a Muxer implementation based on a Chi router.
The returned muxer sets r.Pattern (Go 1.22+) on every matched request. When mux middleware is registered, r.Pattern is set before the middleware runs so observability middleware such as otelhttp can read the matched route for span attributes and metrics. To take advantage of this, register otelhttp as a mux middleware rather than wrapping the mux externally:
mux := loomhttp.NewMuxer()
mux.Use(otelhttp.NewMiddleware("service"))
type ResponseContractCase ¶ added in v1.8.0
type ResponseContractCase struct {
// ID is stable while the service response contract is unchanged.
ID string
// Kind identifies a successful result, informational or service error
// response.
Kind ResponseContractCaseKind
// Transport identifies the response protocol.
Transport ResponseContractTransport
// Selector is the declared status selector that owns this response. It
// describes the case; ValidateResponseContract does not consult it.
Selector StatusSelector
// Domain lists the HTTP statuses this case accepts, as resolved by the
// generator for Selector among the operation's declared selectors. An
// exact selector has its single status as the domain.
Domain []int
// ErrorName is the declared service error name. It is also the expected
// Loom-Error value unless ErrorNameFromStatus is true.
ErrorName string
// ErrorNameFromStatus requires an absent Loom-Error header because the
// response status supplies error identity.
ErrorNameFromStatus bool
// ContentTypes lists the allowed response media types.
ContentTypes []string
// RequiredHeaders lists declared response headers that must be present.
RequiredHeaders []string
// RequiredCookies lists declared response cookies that must be present.
RequiredCookies []string
// Multipart describes the designed multipart request, if present.
Multipart *MultipartRequestContract
// SSE describes stream assertions for an SSE success case.
SSE *SSEResponseContract
// WebSocket describes stream assertions for a WebSocket success case.
WebSocket *WebSocketResponseContract
}
ResponseContractCase describes the HTTP wire invariants for one declared response branch. It does not describe how application code reaches that branch.
type ResponseContractCaseKind ¶ added in v1.8.0
type ResponseContractCaseKind string
ResponseContractCaseKind identifies whether a generated response contract case describes a successful result, an informational response or a service error.
type ResponseContractTransport ¶ added in v1.8.0
type ResponseContractTransport string
ResponseContractTransport identifies the wire protocol validated by a generated response contract case.
type ResponseCookiePolicy ¶ added in v1.9.0
ResponseCookiePolicy applies deployment-specific attributes to a modeled response cookie when Loom prepares it for publication. Typed response metadata may be prepared before its first physical write. Policies may set values such as Domain, Secure, and Expires without moving cookie values out of the generated response contract.
func (ResponseCookiePolicy) Handler ¶ added in v1.9.0
func (p ResponseCookiePolicy) Handler(next http.Handler) http.Handler
Handler makes p available to modeled response cookies written by next. Apply it to one generated method handler or through the generated server's Use method. Handler panics when p is nil.
type ResponseMetadata ¶ added in v1.10.0
type ResponseMetadata struct {
// contains filtered or unexported fields
}
ResponseMetadata owns metadata admission shared by negotiated unary and SSE success. Set, capture and terminal closure are serialized by one owner.
func NewResponseMetadata ¶ added in v1.10.0
func NewResponseMetadata(resolve func(context.Context) (SSEHandshake, error)) *ResponseMetadata
NewResponseMetadata creates the exchange owner with an absent-value resolver. The resolver validates optional or required metadata before publication. A nil resolver supplies status 200. Resolvers must not reenter this owner or its writer.
func (*ResponseMetadata) Capture ¶ added in v1.10.0
func (m *ResponseMetadata) Capture(ctx context.Context) (SSEHandshake, error)
Capture closes unary metadata admission and returns a detached snapshot. A failed capture also closes admission; it never publishes the response.
func (*ResponseMetadata) Close ¶ added in v1.10.0
func (m *ResponseMetadata) Close()
Close closes admission without publication, including handler error paths.
func (*ResponseMetadata) Set ¶ added in v1.10.0
func (m *ResponseMetadata) Set(prepare func() (SSEHandshake, error)) error
Set validates and replaces the prepared snapshot while admission is live. A rejected value preserves the previous snapshot; prepare must not reenter.
type ResponseNegotiationPolicy ¶ added in v1.9.0
type ResponseNegotiationPolicy struct {
// contains filtered or unexported fields
}
ResponseNegotiationPolicy is an immutable list of response media types supported by an HTTP handler.
func NewResponseNegotiationPolicy ¶ added in v1.9.0
func NewResponseNegotiationPolicy(mediaTypes ...string) (ResponseNegotiationPolicy, error)
NewResponseNegotiationPolicy validates mediaTypes and returns a strict response negotiation policy. Supported values must be concrete media types.
func (ResponseNegotiationPolicy) Handler ¶ added in v1.9.0
func (p ResponseNegotiationPolicy) Handler(next http.Handler) http.Handler
Handler rejects requests whose Accept header excludes every configured response media type. Rejections use Loom's default RFC 9457 problem body. Handler panics when p was not constructed by NewResponseNegotiationPolicy.
func (ResponseNegotiationPolicy) MediaTypes ¶ added in v1.9.0
func (p ResponseNegotiationPolicy) MediaTypes() []string
MediaTypes returns a copy of the response media types accepted by the policy.
type RuntimeCORSPolicy ¶ added in v1.5.0
type RuntimeCORSPolicy struct {
// contains filtered or unexported fields
}
RuntimeCORSPolicy is an immutable, validated startup snapshot of a CORS policy supplied by application configuration.
func NewRuntimeCORSPolicy ¶ added in v1.5.0
func NewRuntimeCORSPolicy(policy CORSPolicy) (RuntimeCORSPolicy, error)
NewRuntimeCORSPolicy validates policy and returns an immutable startup snapshot suitable for generated servers declared with RuntimeCORS.
func (RuntimeCORSPolicy) HandlePreflight ¶ added in v1.5.0
func (p RuntimeCORSPolicy) HandlePreflight(w http.ResponseWriter, r *http.Request, allowedMethods []string)
HandlePreflight writes a preflight response using the runtime CORS policy.
func (RuntimeCORSPolicy) Handler ¶ added in v1.5.0
func (p RuntimeCORSPolicy) Handler(next http.HandlerFunc) http.HandlerFunc
Handler wraps next and applies the runtime CORS policy to actual requests.
func (RuntimeCORSPolicy) OptionsHandler ¶ added in v1.9.0
func (p RuntimeCORSPolicy) OptionsHandler(next http.HandlerFunc, allowedMethods []string) http.HandlerFunc
OptionsHandler dispatches browser preflight requests to the runtime CORS policy and ordinary OPTIONS requests to next.
type SSEControl ¶ added in v1.6.0
type SSEControl interface {
Open(context.Context) error
SendComment(context.Context, string) error
}
SSEControl exposes transport lifecycle operations implemented by generated server SSE streams. Endpoint implementations may type assert their stream to this interface without depending on generated concrete types.
type SSEEvent ¶
type SSEEvent struct {
// ID is the last event ID received on the stream, including an empty reset.
ID string
// Type is the event type, or empty when no type was specified.
Type string
// Data is the event payload, with multiple data lines joined by newlines.
Data string
}
SSEEvent represents a parsed server-sent event.
func ParseSSEEvent ¶
ParseSSEEvent parses a single SSE event frame.
type SSEHandshake ¶ added in v1.10.0
type SSEHandshake struct {
// Status is the selected successful HTTP response status.
Status int
// Header contains the validated handshake metadata, copied before publication.
Header http.Header
}
SSEHandshake is the validated status and headers of a successful SSE response.
type SSEMessage ¶
type SSEMessage struct {
// ID is the event identifier to write.
ID string
// Type is the event type to write.
Type string
// Data is the event payload; newlines produce separate data fields.
Data string
// RetryMillis is the reconnection delay in milliseconds.
RetryMillis int64
}
SSEMessage describes an SSE frame to write to an output stream.
type SSEResponseContract ¶ added in v1.8.0
type SSEResponseContract struct {
// Direction is the designed stream direction.
Direction string
// MessageType is the designed streaming result type name.
MessageType string
// DataField is the result field encoded into SSE data, if any.
DataField string
// DataEncoding identifies whether SSE data is JSON or plain text.
DataEncoding string
// IDField is the result field encoded into SSE id, if any.
IDField string
// EventField is the result field encoded into SSE event, if any.
EventField string
// RetryField is the result field encoded into SSE retry, if any.
RetryField string
// IDRequired reports whether every event must include an ID.
IDRequired bool
// EventTypeRequired reports whether every event must include a type.
EventTypeRequired bool
// EventTypes lists allowed projection discriminator values, if constrained.
EventTypes []string
// Terminal identifies the expected stream completion behavior.
Terminal string
}
SSEResponseContract describes the observable wire contract of an SSE stream.
type SSEResponseContractObservation ¶ added in v1.8.0
type SSEResponseContractObservation struct {
// Response is the HTTP handshake response.
Response *http.Response
// Events contains parsed SSE frames observed before completion.
Events []SSEEvent
// TerminalError is the final error returned by the stream reader.
TerminalError error
}
SSEResponseContractObservation contains the response and frames produced by one consumer-owned SSE scenario.
type SSEStreamOption ¶ added in v1.10.0
type SSEStreamOption func(*SSEStreamWriter)
SSEStreamOption configures a writer before its first operation.
func WithSSEExchange ¶ added in v1.10.0
func WithSSEExchange(exchange *ExchangeWriter) SSEStreamOption
WithSSEExchange associates first-open admission with the shared HTTP exchange.
func WithSSEHandshake ¶ added in v1.10.0
func WithSSEHandshake(resolve func(context.Context) (SSEHandshake, error)) SSEStreamOption
WithSSEHandshake installs an immutable first-open resolver. It runs under writer ownership with the request context and must not reenter the writer; it validates the selected contract.
func WithSSEResponseMetadata ¶ added in v1.10.0
func WithSSEResponseMetadata(metadata *ResponseMetadata) SSEStreamOption
WithSSEResponseMetadata attaches the exchange's existing metadata owner to the SSE writer. Both use the same admission lock; metadata must be nonnil.
type SSEStreamReader ¶ added in v1.3.0
type SSEStreamReader struct {
// contains filtered or unexported fields
}
SSEStreamReader adapts the SSE library iterator to context-aware reads. The library owns framing, parsing, event limits, and event memory. Reads are serialized. Closing the response body must unblock an active Read, as required by net/http.Response.Body.
func NewSSEStreamReader ¶ added in v1.3.0
func NewSSEStreamReader(body io.ReadCloser) *SSEStreamReader
NewSSEStreamReader returns a stream reader with the library's default 64 KiB event limit. The caller must call Close to release the body and iterator.
func (*SSEStreamReader) Close ¶ added in v1.3.0
func (r *SSEStreamReader) Close() error
Close closes the response body once and releases the library iterator. It waits for any active read to finish and returns the body's close error.
func (*SSEStreamReader) ReadEvent ¶ added in v1.3.0
func (r *SSEStreamReader) ReadEvent(ctx context.Context) (SSEEvent, error)
ReadEvent returns the next parsed SSE event. EOF discards an incomplete final event. Canceling ctx closes the stream and returns ctx.Err unless a complete event was already obtained. Subsequent reads of a closed stream return EOF.
type SSEStreamWriter ¶ added in v1.6.0
type SSEStreamWriter struct {
// contains filtered or unexported fields
}
SSEStreamWriter owns serialized writes for a generated server SSE stream.
func NewSSEStreamWriter ¶ added in v1.6.0
func NewSSEStreamWriter( w http.ResponseWriter, requestCtx context.Context, transport loomtransport.TransportKind, policy StreamWritePolicy, opts ...SSEStreamOption, ) *SSEStreamWriter
NewSSEStreamWriter returns a shared writer for a generated server SSE stream.
func (*SSEStreamWriter) ClaimFailure ¶ added in v1.10.0
func (s *SSEStreamWriter) ClaimFailure() bool
ClaimFailure closes admission before a handler routes its endpoint error and reports whether the successful SSE response had already started. It waits for an admitted writer operation, preserves any prior transport failure, and does not write, inspect cancellation, or dispatch observations. Defer End separately to finish cleanup and preserve handler panic precedence.
func (*SSEStreamWriter) Close ¶ added in v1.6.0
func (s *SSEStreamWriter) Close() error
Close publishes a successful zero-event response using the request context and closes admission. An existing terminal outcome is a nil no-op.
func (*SSEStreamWriter) Complete ¶ added in v1.10.0
func (s *SSEStreamWriter) Complete(ctx context.Context, prepare func() (SSEMessage, error)) error
Complete admits one terminal SSE operation. prepare executes under write ownership and must not reenter the writer. An encoding error leaves the stream usable. Once preparation succeeds, every write/flush outcome is terminal. A nil prepare publishes the successful handshake without a frame.
func (*SSEStreamWriter) Context ¶ added in v1.6.0
func (s *SSEStreamWriter) Context() context.Context
Context returns the inbound request context associated with the stream.
func (*SSEStreamWriter) End ¶ added in v1.10.0
func (s *SSEStreamWriter) End()
End finalizes a handler's writer without opening an unused stream. Defer End so the original handler panic keeps precedence if an observer also panics.
func (*SSEStreamWriter) FinalizeSuccess ¶ added in v1.10.0
func (s *SSEStreamWriter) FinalizeSuccess(ctx context.Context) error
FinalizeSuccess publishes a zero-event success and closes live admission. Existing terminal outcomes are preserved as a nil no-op.
func (*SSEStreamWriter) Observation ¶ added in v1.10.0
func (s *SSEStreamWriter) Observation() *loomtransport.StreamObserver
Observation returns the writer's immutable stream identity for protocol-level events. It does not change per-call cancellation or physical lifecycle state.
func (*SSEStreamWriter) Open ¶ added in v1.6.0
func (s *SSEStreamWriter) Open(ctx context.Context) error
Open commits and flushes the successful SSE response once.
func (*SSEStreamWriter) SendComment ¶ added in v1.6.0
func (s *SSEStreamWriter) SendComment(ctx context.Context, text string) error
SendComment writes and flushes one SSE comment frame.
func (*SSEStreamWriter) SetHandshake ¶ added in v1.10.0
func (s *SSEStreamWriter) SetHandshake(prepare func() (SSEHandshake, error)) error
SetHandshake validates and replaces unopened, live handshake metadata under writer ownership. prepare must not reenter the writer. Failure preserves the prior snapshot; opened or terminal admission rejects before invoking prepare.
func (*SSEStreamWriter) Started ¶ added in v1.6.0
func (s *SSEStreamWriter) Started() bool
Started reports whether the successful SSE response has been committed.
func (*SSEStreamWriter) Suppress ¶ added in v1.10.0
func (s *SSEStreamWriter) Suppress() error
Suppress closes live admission without publication or inspecting cancellation. Only the first admitted call succeeds; callers may report suppression after nil.
func (*SSEStreamWriter) WriteEvent ¶ added in v1.6.0
WriteEvent serializes and flushes one generated SSE event. The stream becomes terminal when the callback fails after writing any bytes, when a write to the response itself fails, or when the flush fails: later calls return ErrSSEStreamClosed wrapping the original failure and write nothing, so a partially written frame is never followed by another event. A callback error returned before any byte was written, such as an encoding failure, is returned as is and leaves the stream usable. Cancellation observed before an operation starts does not end the stream. If ctx is canceled after the frame was serialized, WriteEvent returns ctx.Err() without flushing; the frame stays buffered and may still reach the client, so callers must not re-send it.
type Server ¶
Server is the HTTP server interface used to wrap the server handlers with the given middleware.
type Servers ¶
type Servers []Server
Servers is a list of servers.
type StatusCoder ¶ added in v1.9.0
type StatusCoder interface {
// StatusCode returns the HTTP status code used to encode the response
// when not defined in the design.
StatusCode() int
}
StatusCoder is implemented by an error response object to provide the response HTTP status code.
func NewErrorResponse ¶
func NewErrorResponse(ctx context.Context, err error) StatusCoder
NewErrorResponse creates the default RFC 9457 problem document for err.
type StatusSelector ¶ added in v1.10.0
type StatusSelector struct {
// Code is an exact status in the range 100 through 599, or zero when
// Class is set.
Code int
// Class is a status class digit from 1 through 5, -1 for fallback,
// or zero when Code is set.
Class int
}
StatusSelector identifies an exact HTTP status, a status class, or the fallback response. Exactly one of Code and Class is set.
func SelectFinal ¶ added in v1.10.0
func SelectFinal(keys []StatusSelector, code int) (StatusSelector, bool)
SelectFinal selects a declared response for code in the range 200 through 599. Exact status takes precedence over class, then fallback, independently of declaration order. It returns false when no declared selector matches.
func SelectInformational ¶ added in v1.10.0
func SelectInformational(keys []StatusSelector, code int) (StatusSelector, bool)
SelectInformational selects a declared informational response for code in the range 100 through 199, excluding 101. Exact status takes precedence over class 1; fallback is never informational. This selects observed responses, including 100, rather than defining the server's authored emission domain.
type StatusViolationError ¶ added in v1.10.0
type StatusViolationError struct {
// Code is the attempted response status.
Code int
// Selector is the response selector whose domain rejected Code.
Selector StatusSelector
}
StatusViolationError reports a status outside a response selector's final domain. It is a framework error and carries no designed error name.
func (*StatusViolationError) Error ¶ added in v1.10.0
func (e *StatusViolationError) Error() string
Error describes the rejected status and response selector.
type StreamWritePolicy ¶ added in v1.6.0
type StreamWritePolicy struct {
// contains filtered or unexported fields
}
StreamWritePolicy configures the maximum duration of each server-stream network write or flush. The zero value preserves unbounded writes.
func NewStreamWritePolicy ¶ added in v1.6.0
func NewStreamWritePolicy(timeout time.Duration) (StreamWritePolicy, error)
NewStreamWritePolicy returns an immutable server-stream write policy.
func (StreamWritePolicy) Timeout ¶ added in v1.6.0
func (p StreamWritePolicy) Timeout() time.Duration
Timeout returns the maximum duration allowed for each write or flush.
type TextBranch ¶ added in v1.10.0
type TextBranch struct {
// View reads the raw value owned by this branch's binding.
View func() (ParamValue, error)
// Shape describes its raw-to-JSON conversion.
Shape ParamBranchShape
// Member tests schema membership on exact JSON data.
Member func(jsontext.Value) (bool, error)
// Evaluate returns evaluated object members for the matching JSON value.
Evaluate func(jsontext.Value) ([]string, error)
// Assign converts and validates into a private typed candidate.
Assign func(ParamValue) (bool, error)
}
TextBranch supplies pure schema membership and private typed conversion. It does not select a union member or publish a decoded candidate.
func (TextBranch) Annotations ¶ added in v1.10.0
func (b TextBranch) Annotations() (TextUnionAnnotations, error)
Annotations returns the decoded instance members and schema annotations for a matching branch. It uses the same immutable raw view and JSON projection as Schema, so sibling parameter keys cannot enter the logical instance. Scalars and sequences bypass object closure. Call only after schema selection succeeds.
func (TextBranch) Decode ¶ added in v1.10.0
func (b TextBranch) Decode() (bool, error)
Decode converts into the branch's private candidate without publishing it.
func (TextBranch) Schema ¶ added in v1.10.0
func (b TextBranch) Schema() (bool, error)
Schema checks the raw value against the branch schema without typed conversion.
type TextUnionAnnotations ¶ added in v1.10.0
type TextUnionAnnotations struct {
// Members contains the present object members in the branch's raw view.
Members []string
// Evaluated contains members evaluated by the matching schema.
Evaluated []string
}
TextUnionAnnotations describes one matching branch's logical instance. Both sets use decoded member names at the same root location. Scalars and sequences have no members. The codec owner excludes sibling bindings.
type TextUnionBranch ¶ added in v1.10.0
type TextUnionBranch struct {
// Schema checks codec grammar and schema membership without Go widths.
Schema func() (bool, error)
// Decode converts and validates into a private candidate.
Decode func() (bool, error)
// Annotations returns the matching schema's evaluated-member annotations
// together with its instance members. Closed unions require this callback.
Annotations func() (TextUnionAnnotations, error)
}
TextUnionBranch supplies independent predicates over one branch's raw view. Decoded values must remain private until selection succeeds. Captured raw views and annotation slices must remain immutable for this input.
func ComposeTextUnion ¶ added in v1.10.0
func ComposeTextUnion(name string, branches []TextUnionBranch, closed bool, assign func(int) (bool, error)) TextUnionBranch
ComposeTextUnion makes a nested union into one outer candidate. Schema membership counts only inner schemas; decoding requires agreement in both domains before assign receives the selected index. assign must write only to a private destination. Ordinary nested union mismatches reject this candidate; evaluator and assignment errors propagate. Each predicate runs at most once for this input, so nesting does not repeatedly evaluate descendants. Construct a fresh candidate for each input; captured raw views must remain immutable. Closed unions check annotations after counting the original inner branches. The selected annotations are retained for enclosing unions without reevaluation.
type UnaryHandlerSpec ¶ added in v1.8.0
type UnaryHandlerSpec[Payload, Result any] struct { // Service is the designed service name. Service string // Method is the designed service method name. Method string // Decode converts an HTTP request into the service payload. A nil // function supplies the zero value of Payload. Decode func(*http.Request) (Payload, error) // Invoke calls the typed service endpoint. Invoke func(context.Context, Payload) (Result, error) // EncodeResponse writes a successful typed result. EncodeResponse func(context.Context, http.ResponseWriter, Result) error // EncodeError writes a request or endpoint error. EncodeError func(context.Context, http.ResponseWriter, error) error // HandleFailure receives errors that cannot be written as responses. HandleFailure func(context.Context, http.ResponseWriter, error) }
UnaryHandlerSpec defines the typed adapters and runtime policy for one ordinary unary HTTP endpoint.
type UnaryResult ¶ added in v1.8.0
type UnaryResult[Result any] struct { // Value is the raw value returned by the service endpoint. Value any }
UnaryResult carries an endpoint result to its typed response adapter. Result identifies the designed result type, and Value retains the raw endpoint value for generated validation.
type Upgrader ¶
type Upgrader interface {
// Upgrade upgrades the HTTP connection to the websocket protocol.
Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*websocket.Conn, error)
}
Upgrader is an HTTP connection that is able to upgrade to websocket.
type WebSocketConfig ¶ added in v1.10.0
type WebSocketConfig struct {
// contains filtered or unexported fields
}
WebSocketConfig configures one physical WebSocket connection. Its zero value selects default limits and no hook. Expanded limits apply even if the hook changes Gorilla's framing limit.
func NewWebSocketConfig ¶ added in v1.10.0
func NewWebSocketConfig(limits WebSocketLimits, configure ConnConfigureFunc) (WebSocketConfig, error)
NewWebSocketConfig validates limits and configures the attachment hook. Negative limits reject. MaxMessageBytes must not exceed MaxInt64/2, and the total byte budget must be at least twice the resolved message maximum.
func (WebSocketConfig) MaxBufferedBytes ¶ added in v1.10.0
func (c WebSocketConfig) MaxBufferedBytes() int64
MaxBufferedBytes returns the total raw message budget, including one flight.
func (WebSocketConfig) MaxBufferedMessages ¶ added in v1.10.0
func (c WebSocketConfig) MaxBufferedMessages() int
MaxBufferedMessages returns the queued/current-decode message-count limit.
func (WebSocketConfig) MaxMessageBytes ¶ added in v1.10.0
func (c WebSocketConfig) MaxMessageBytes() int64
MaxMessageBytes returns the maximum expanded size of one inbound message.
type WebSocketLimits ¶ added in v1.10.0
type WebSocketLimits struct {
// MaxMessageBytes bounds one expanded message; zero means 32 MiB.
MaxMessageBytes int64
// MaxBufferedBytes includes queued/current-decode payload bytes and one
// maximum in-flight message; zero means twice MaxMessageBytes.
MaxBufferedBytes int64
// MaxBufferedMessages bounds queued/current-decode records, including
// empty messages; zero means 256. One additional message may be in flight.
MaxBufferedMessages int
}
WebSocketLimits bounds inbound raw messages retained by one connection. Zero fields select defaults. These limits exclude decoded Go objects, allocator overhead and values retained by ReadMessage callers.
type WebSocketResponseContract ¶ added in v1.8.0
type WebSocketResponseContract struct {
// Direction is the designed stream direction.
Direction string
// InboundMessageType is the designed client-to-server message type name.
InboundMessageType string
// OutboundMessageType is the designed server-to-client message type name.
OutboundMessageType string
// HandshakeHeaders lists required WebSocket upgrade response headers.
HandshakeHeaders []string
// Terminal identifies the expected stream completion behavior.
Terminal string
}
WebSocketResponseContract describes the observable wire contract of a WebSocket stream.
type WebSocketResponseContractObservation ¶ added in v1.8.0
type WebSocketResponseContractObservation struct {
// Response is the HTTP upgrade response.
Response *http.Response
// Messages contains server-to-client JSON messages in wire order.
Messages []jsontext.Value
// TerminalError is the final error returned by the WebSocket reader. It is
// nil when the contract terminates with one final response message.
TerminalError error
}
WebSocketResponseContractObservation contains the handshake, JSON messages, and terminal read result produced by one consumer-owned WebSocket scenario.
type WebSocketStream ¶ added in v1.3.0
type WebSocketStream struct {
// contains filtered or unexported fields
}
WebSocketStream owns one physical reader, a bounded inbox and terminal shutdown for a WebSocket connection. Call SetConn to attach it. Only one application goroutine may receive at a time; writes are serialized.
func NewServerWebSocketStream ¶ added in v1.10.0
func NewServerWebSocketStream(ctx context.Context, kind loomtransport.TransportKind, config WebSocketConfig, policies ...StreamWritePolicy) *WebSocketStream
NewServerWebSocketStream allocates a server connection owner with immutable observation identity. Client connections use NewWebSocketStream and never inherit inbound request observation through SetConn.
func NewWebSocketStream ¶ added in v1.3.0
func NewWebSocketStream(config WebSocketConfig, policies ...StreamWritePolicy) *WebSocketStream
NewWebSocketStream allocates the shared connection owner with config. Attach a dialed or upgraded connection with SetConn before reading or writing.
func (*WebSocketStream) Close ¶ added in v1.3.0
func (s *WebSocketStream) Close() error
Close terminally releases the connection immediately. The first terminal transition owns the cause; repeated calls return its recorded cleanup error. Close before attachment rejects and releases any later connection.
func (*WebSocketStream) CloseWithFinalJSON ¶ added in v1.10.0
func (s *WebSocketStream) CloseWithFinalJSON(value any) error
CloseWithFinalJSON terminally writes value, waits best effort for peer termination, and releases the connection. Its one-second deadline covers write-lock acquisition, the write and the wait, independently of the normal write policy. Physical release is unconditional. A successful write followed by wait expiration or a peer read failure adds no cleanup error; this is not an acknowledgement of service processing. HTTP client Close uses nil for its final JSON-null framing. CloseAndRecv instead writes null nonterminally so it can receive the final service reply. An already-sent native close frame skips the wait and adds no cleanup error.
func (*WebSocketStream) CloseWithStatus ¶ added in v1.10.0
func (s *WebSocketStream) CloseWithStatus(code int, reason string) error
CloseWithStatus terminally attempts a close control frame, then releases the socket even when the bounded one-second write fails. Codes must be standard sendable close codes or in 3000..4999; reason must be valid UTF-8 of at most 123 bytes. Invalid arguments still release the socket and return an error. Repeated valid calls preserve the first terminal cause and cleanup result. An already-sent native close frame adds no cleanup error.
func (*WebSocketStream) Conn ¶ added in v1.3.0
func (s *WebSocketStream) Conn() *websocket.Conn
Conn returns the wrapped Gorilla WebSocket connection. The stream owns all physical reads; install read handlers in the configuration hook before attachment instead of reading or mutating reader state through Conn.
func (*WebSocketStream) DecodeMessage ¶ added in v1.10.0
DecodeMessage receives one message and holds its byte/count reservation until decode returns. The callback must not retain data or call another receive. Its error is returned unchanged and does not itself terminate the connection. Use this seam for protocol decoders that must distinguish decode errors from connection failures. Like ReadJSON, at most one caller may receive at a time.
func (*WebSocketStream) ReadJSON ¶ added in v1.3.0
func (s *WebSocketStream) ReadJSON(ctx context.Context, value any) error
ReadJSON receives and decodes one message while retaining its admission reservation through decoding. Empty/whitespace input returns io.ErrUnexpectedEOF. Decode failures are recoverable; connection failures are terminal. An already-done ctx is nondestructive; active cancellation closes.
func (*WebSocketStream) ReadMessage ¶ added in v1.10.0
func (s *WebSocketStream) ReadMessage(ctx context.Context) ([]byte, error)
ReadMessage receives one text or binary message. Ownership of the returned bytes passes to the caller; their admission reservation is released on return. A natural peer read failure releases the socket immediately, preserves already admitted FIFO messages for live-context readers, and then returns its stable cause. Explicit close and overload reject queued work. Expanded-message overflow wraps websocket.ErrReadLimit; aggregate overflow wraps ErrWebSocketBufferFull. Only one caller may receive at a time.
func (*WebSocketStream) RunHandler ¶ added in v1.10.0
func (s *WebSocketStream) RunHandler(run func() error, reportCloseError func(error)) (err error)
RunHandler runs one handler and owns its deferred connection cleanup without forcing a lazy upgrade. Success closes with 1000; an error or panic closes with 1011 and a generic reason. The original panic is propagated even if the cleanup reporter panics. A nonnil reporter receives only cleanup failures, preserving the handler error; nil joins cleanup failures into the returned error. While unwinding a panic, the panic retains precedence over cleanup.
func (*WebSocketStream) SetConn ¶ added in v1.3.0
func (s *WebSocketStream) SetConn(ctx context.Context, conn *websocket.Conn, cancel context.CancelFunc) error
SetConn configures and adopts conn for ctx's connection lifetime. It invokes the hook before starting the sole physical reader. cancel, when nonnil, is called on terminal shutdown and is also passed to the hook. The hook owns releasing its input when it returns a replacement. A nil result closes input. Reattaching the same connection is a no-op. A different or late connection is rejected and closed. Cancellation during configuration cannot revive a stream.
func (*WebSocketStream) WriteJSON ¶ added in v1.3.0
func (s *WebSocketStream) WriteJSON(ctx context.Context, v any) (err error)
WriteJSON writes one JSON WebSocket frame while honoring ctx cancellation. Concurrent calls are serialized. It returns ErrWebSocketStreamClosed when no connection is attached or the stream has been closed.
Source Files
¶
- client.go
- client_debug_response.go
- cors.go
- derived_head.go
- doc.go
- encoding.go
- error.go
- exchange_writer.go
- file_response.go
- file_server.go
- form.go
- form_branch.go
- handler_lifecycle.go
- header.go
- informational_client.go
- json_field.go
- media_codec.go
- media_contract.go
- media_form.go
- media_multipart.go
- multipart.go
- multipart_content.go
- multipart_metadata.go
- multipart_param.go
- multipart_write.go
- mux.go
- param_branch.go
- param_branch_annotations.go
- param_codec.go
- param_cookie.go
- param_fault.go
- param_form.go
- param_header.go
- param_pairs.go
- param_path.go
- param_tokens.go
- path.go
- request_body_null.go
- request_body_policy.go
- request_cookie.go
- request_encoding.go
- request_metadata.go
- response_body.go
- response_contract.go
- response_cookie_policy.go
- response_metadata.go
- response_negotiation.go
- server.go
- sse.go
- sse_event_response.go
- sse_writer.go
- status_selector.go
- stream_policy.go
- union_text.go
- union_text_nested.go
- websocket.go
- websocket_config.go
- websocket_reader.go
- websocket_shutdown.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package cli contains runtime helpers for generated HTTP command-line clients.
|
Package cli contains runtime helpers for generated HTTP command-line clients. |
|
Package codegen generates HTTP servers, clients, and OpenAPI specifications from an evaluated Loom design.
|
Package codegen generates HTTP servers, clients, and OpenAPI specifications from an evaluated Loom design. |
|
openapi
Package openapi provides the active schema model and shared helpers used to generate OpenAPI 3.1 and 3.2 specifications from Loom designs.
|
Package openapi provides the active schema model and shared helpers used to generate OpenAPI 3.1 and 3.2 specifications from Loom designs. |
|
openapi/v3
Package openapiv3 contains the algorithms and data structures used to generate OpenAPI 3.1 and 3.2 specifications from Loom designs.
|
Package openapiv3 contains the algorithms and data structures used to generate OpenAPI 3.1 and 3.2 specifications from Loom designs. |
|
Package middleware contains HTTP middlewares that wrap a HTTP handler to provide ancillary functionality such as capturing HTTP details into the request context or printing debug information on incoming requests.
|
Package middleware contains HTTP middlewares that wrap a HTTP handler to provide ancillary functionality such as capturing HTTP details into the request context or printing debug information on incoming requests. |
|
otel
Package otel provides thin OpenTelemetry middleware helpers for Loom HTTP servers and clients.
|
Package otel provides thin OpenTelemetry middleware helpers for Loom HTTP servers and clients. |