Documentation
¶
Overview ¶
Package http provides Foundry's HTTP transport and application kernel while retaining interoperability with standard net/http handlers.
Index ¶
- Constants
- Variables
- func AbsoluteURL(origin Origin, relative string) (string, error)
- func ActorKeys() keyspace.Codec[ActorKey]
- func ApplyMiddleware(handler stdhttp.Handler, middlewares ...Middleware) (stdhttp.Handler, error)
- func AssetsModule(name foundation.ProviderID, key foundation.Key[*Assets], config AssetsConfig) foundation.Module
- func AuthenticatedEndpointPattern[P, Q, B, M, R any](endpoint AuthenticatedEndpoint[P, Q, B, M, R]) string
- func AuthenticatedRouteURL[P, M any](r AuthenticatedRoute[P, M], path P) (string, error)
- func ClientIP(ctx context.Context) netip.Addr
- func DecodeQuery[Q any](d Query[Q], ctx context.Context, raw string, limits QueryLimits) (Q, error)
- func EncodeQuery[Q any](d Query[Q], ctx context.Context, input Q, limits QueryLimits) (string, error)
- func EndpointPattern[P, Q, B, R any](e Endpoint[P, Q, B, R]) string
- func ErrorResponseJSON() contract.JSON[ErrorResponse]
- func IsHTMLNavigation(r *stdhttp.Request, name string) bool
- func IsSecure(r *stdhttp.Request) bool
- func LastEventID(ctx context.Context) (string, bool)
- func MessageDefinitions() []i18n.MessageDefinition
- func Module(name foundation.ProviderID, key foundation.Key[*Server], config ServerConfig, ...) foundation.Module
- func OptionalEndpointPattern[P, Q, B, M, R any](endpoint OptionalAuthenticationEndpoint[P, Q, B, M, R]) string
- func OptionalRouteURL[P, M any](r OptionalAuthenticationRoute[P, M], path P) (string, error)
- func PathPattern[P any](p Path[P]) string
- func PathURL[P any](p Path[P], parameters P) (string, error)
- func PeerIP(request *stdhttp.Request) netip.Addr
- func PermanentAuthenticatedEndpointURL[P, Q, B, S, R any](e SignedAuthenticatedEndpoint[P, Q, B, S, R], ctx context.Context, ...) (string, error)
- func PermanentAuthenticatedRouteURL[P, S any](r SignedAuthenticatedRoute[P, S], ctx context.Context, origin Origin, path P) (string, error)
- func PermanentEndpointURL[P, Q, B, R any](e SignedEndpoint[P, Q, B, R], ctx context.Context, origin Origin, path P, ...) (string, error)
- func PermanentRouteURL[P any](r SignedRoute[P], ctx context.Context, origin Origin, path P) (string, error)
- func PublicURL(ctx context.Context, relative string) (string, error)
- func RateLimitExceeded(decision ratelimit.Decision) error
- func RegisterEndpoint[P, Q, B, R any](r *foundation.Registrar, key foundation.Key[*Router], ...) error
- func RegisterIdempotentEndpoint[P, Q, B, R any](r *foundation.Registrar, key foundation.Key[*Router], ...) error
- func RegisterMiddleware(r *foundation.Registrar, key foundation.Key[*Router], middleware Middleware) error
- func RegisterRoute[P any](r *foundation.Registrar, key foundation.Key[*Router], declaration Route[P], ...) error
- func RegisterRouter(r *foundation.Registrar, key foundation.Key[*Router]) error
- func RegisterRouterWithRoutes(r *foundation.Registrar, key foundation.Key[*Router], ...) error
- func RegisterSPA(r *foundation.Registrar, key foundation.Key[*Router], id RouteID, ...) error
- func RegisterSignedEndpoint[P, Q, B, R any](r *foundation.Registrar, key foundation.Key[*Router], ...) error
- func RegisterSignedRoute[P any](r *foundation.Registrar, key foundation.Key[*Router], ...) error
- func RelativeAuthenticatedEndpointURL[P, Q, B, S, R any](e SignedAuthenticatedEndpoint[P, Q, B, S, R], ctx context.Context, path P, ...) (string, error)
- func RelativeAuthenticatedRouteURL[P, S any](r SignedAuthenticatedRoute[P, S], ctx context.Context, path P, ...) (string, error)
- func RelativeEndpointURL[P, Q, B, R any](e SignedEndpoint[P, Q, B, R], ctx context.Context, path P, query Q, ...) (string, error)
- func RelativeRouteURL[P any](r SignedRoute[P], ctx context.Context, path P, expires time.Time) (string, error)
- func RequestID(ctx context.Context) attribution.RequestID
- func RoutePattern[P any](r Route[P]) string
- func RouteURL[P any](r Route[P], parameters P) (string, error)
- func ServeEvents[T any](w stdhttp.ResponseWriter, r *stdhttp.Request, descriptor contract.JSON[T], ...) error
- func SignedAuthenticatedEndpointPattern[P, Q, B, S, R any](e SignedAuthenticatedEndpoint[P, Q, B, S, R]) string
- func SignedAuthenticatedRouteURL[P, S any](r SignedAuthenticatedRoute[P, S], ctx context.Context, origin Origin, path P, ...) (string, error)
- func SignedEndpointPattern[P, Q, B, R any](e SignedEndpoint[P, Q, B, R]) string
- func SignedRoutePattern[P any](r SignedRoute[P]) string
- func SignedRouteURL[P any](r SignedRoute[P], ctx context.Context, origin Origin, path P, ...) (string, error)
- func ValidateAuthenticated[P, Q, B, M, R any](e AuthenticatedEndpoint[P, Q, B, M, R]) error
- func ValidateAuthenticatedIdempotent[P, Q, B, M, R any](e AuthenticatedIdempotentEndpoint[P, Q, B, M, R]) error
- func ValidateAuthenticatedRoute[P, M any](r AuthenticatedRoute[P, M]) error
- func ValidateBodyDescriptor[B any](body Body[B]) error
- func ValidateEndpoint[P, Q, B, R any](e Endpoint[P, Q, B, R]) error
- func ValidateIdempotent[P, Q, B, R any](e IdempotentEndpoint[P, Q, B, R]) error
- func ValidateMultipart[B any](d Multipart[B]) error
- func ValidateOptional[P, Q, B, M, R any](e OptionalAuthenticationEndpoint[P, Q, B, M, R]) error
- func ValidateOptionalRoute[P, M any](r OptionalAuthenticationRoute[P, M]) error
- func ValidateQueryDescriptor[Q any](d Query[Q]) error
- func ValidateResponse[R any](r Response[R]) error
- func ValidateRoute[P any](r Route[P]) error
- func ValidateSigned[P, Q, B, R any](e SignedEndpoint[P, Q, B, R]) error
- func ValidateSignedAuthenticated[P, Q, B, S, R any](e SignedAuthenticatedEndpoint[P, Q, B, S, R]) error
- func ValidateSignedAuthenticatedRoute[P, S any](r SignedAuthenticatedRoute[P, S]) error
- func ValidateSignedRoute[P any](r SignedRoute[P]) error
- func ValidateTicketAuthenticated[P, Q, B, M, R any](e TicketEndpoint[P, Q, B, M, R]) error
- func WriteError(w stdhttp.ResponseWriter, r *stdhttp.Request, err error) error
- type Access
- type ActorKey
- type ActorOption
- type AssetExtension
- type AssetMount
- type AssetPath
- type AssetRouteInfo
- type AssetSource
- type Assets
- type AssetsConfig
- type AuthenticatedBinding
- type AuthenticatedBindingTransport
- func AfterAuthenticatedValidation[P, Q, B, S, R any](transport AuthenticatedHandlerTransport[P, Q, B, S, R]) AuthenticatedBindingTransport[P, Q, B, S, R]
- func ForAuthenticatedBinding[P, Q, B, S, R any](endpoint AuthenticatedEndpoint[P, Q, B, S, R]) AuthenticatedBindingTransport[P, Q, B, S, R]
- func ForOptionalBinding[P, Q, B, S, R any](endpoint OptionalAuthenticationEndpoint[P, Q, B, S, R]) AuthenticatedBindingTransport[P, Q, B, value.Optional[S], R]
- func ForSignedAuthenticatedBinding[P, Q, B, S, R any](endpoint SignedAuthenticatedEndpoint[P, Q, B, S, R]) AuthenticatedBindingTransport[P, Q, B, S, R]
- func ForSignedOptionalBinding[P, Q, B, S, R any](endpoint SignedAuthenticatedEndpoint[P, Q, B, value.Optional[S], R]) AuthenticatedBindingTransport[P, Q, B, value.Optional[S], R]
- type AuthenticatedEndpoint
- func Authenticated[P, Q, B, M, R any](endpoint Endpoint[P, Q, B, R], binding GuardBinding[M], ...) AuthenticatedEndpoint[P, Q, B, M, R]
- func AuthorizeActor[P, Q, B, M, R any](e AuthenticatedEndpoint[P, Q, B, M, R], ...) AuthenticatedEndpoint[P, Q, B, M, R]
- func ConfigureAuthenticated[P, Q, B, M, R any](endpoint AuthenticatedEndpoint[P, Q, B, M, R], options ...GuardOption[M]) AuthenticatedEndpoint[P, Q, B, M, R]
- func PrepareAuthenticated[P, Q, B, M, R any](e AuthenticatedEndpoint[P, Q, B, M, R], prepare Preparation[P, Q, B]) AuthenticatedEndpoint[P, Q, B, M, R]
- func RequireAuthentication[P, Q, B, M, R any](endpoint Endpoint[P, Q, B, R], authentication *Authentication, ...) AuthenticatedEndpoint[P, Q, B, M, R]
- type AuthenticatedHandlerTransport
- type AuthenticatedIdempotentEndpoint
- func AuthenticatedIdempotentHeaders[P, Q, B, M, R any](e AuthenticatedIdempotentEndpoint[P, Q, B, M, R], ...) AuthenticatedIdempotentEndpoint[P, Q, B, M, R]
- func IdempotentAuthenticated[P, Q, B, M, R any](endpoint AuthenticatedEndpoint[P, Q, B, M, R], store *idempotency.Store, ...) AuthenticatedIdempotentEndpoint[P, Q, B, M, R]
- type AuthenticatedRoute
- type Authentication
- type AuthenticationInfo
- type Binding
- type BindingTransport
- func AfterValidation[P, Q, B, R any](transport HandlerTransport[P, Q, B, R]) BindingTransport[P, Q, B, R]
- func ForBinding[P, Q, B, R any](endpoint Endpoint[P, Q, B, R]) BindingTransport[P, Q, B, R]
- func ForSignedBinding[P, Q, B, R any](endpoint SignedEndpoint[P, Q, B, R]) BindingTransport[P, Q, B, R]
- type Body
- func EmptyBody() Body[NoBody]
- func FormBody[B any](fields Query[B]) Body[B]
- func JSONBody[B any](descriptor contract.JSON[B]) Body[B]
- func MFARecoveryBody() Body[MFARecoveryRequest]
- func MFATOTPBody() Body[MFATOTPRequest]
- func MultipartBody[B any](descriptor Multipart[B]) Body[B]
- func RawRequestBody(media MediaType, additional ...MediaType) Body[RawBody]
- func RefreshTokenBody() Body[RefreshTokenRequest]
- func RefreshTokenCookie(cookie RefreshCookie) Body[RefreshTokenRequest]
- func RefreshTokenCookieLogout(cookie RefreshCookie) Body[RefreshCookieLogoutRequest]
- type BrotliQuality
- type BrotliWindow
- type BrowserSessionConfig
- type BrowserSessions
- func (b *BrowserSessions[M, K]) Authentication() *Authentication
- func (b *BrowserSessions[M, K]) CompleteMFA(ctx context.Context, factor auth.SecondFactor[M, K], ...) (session.Info[M, K], error)
- func (b *BrowserSessions[M, K]) Guard() auth.Guard[M]
- func (b *BrowserSessions[M, K]) Impersonate(ctx context.Context, impersonation *session.Impersonation[M, K, M, K], ...) (session.Info[M, K], error)
- func (b *BrowserSessions[M, K]) Login(ctx context.Context, proof auth.Proof[M, K], options session.IssueOptions) (session.Info[M, K], error)
- func (b *BrowserSessions[M, K]) Logout(ctx context.Context) error
- func (b *BrowserSessions[M, K]) Middleware() Middleware
- func (b *BrowserSessions[M, K]) RefuseImpersonation() Middleware
- func (b *BrowserSessions[M, K]) RequirePasswordConfirmation(within time.Duration) Middleware
- func (b *BrowserSessions[M, K]) Rotate(ctx context.Context) (session.Info[M, K], error)
- func (b *BrowserSessions[M, K]) StopImpersonating(ctx context.Context, impersonation *session.Impersonation[M, K, M, K]) (session.Info[M, K], error)
- func (b *BrowserSessions[M, K]) Validate() error
- type CORSConfig
- type CORSPath
- type CSPConfig
- type CSPNonce
- type CSPPolicy
- type CSPReportGroup
- type CSPReportURI
- type CSPSandboxToken
- type CSPSource
- func CSPAny() CSPSource
- func CSPHostSource(pattern string) CSPSource
- func CSPNonceSource() CSPSource
- func CSPNone() CSPSource
- func CSPReportSample() CSPSource
- func CSPSHA256(digest [32]byte) CSPSource
- func CSPSHA384(digest [48]byte) CSPSource
- func CSPSHA512(digest [64]byte) CSPSource
- func CSPSchemeSource(scheme string) CSPSource
- func CSPSelf() CSPSource
- func CSPStrictDynamic() CSPSource
- func CSPUnsafeEval() CSPSource
- func CSPUnsafeHashes() CSPSource
- func CSPUnsafeInline() CSPSource
- func CSPWasmUnsafeEval() CSPSource
- type CSRFConfig
- type CachePolicy
- type CacheVisibility
- type CompressionConfig
- type CompressionEncoder
- type ContentEncoding
- type Cookie
- func (c Cookie[V]) Clear(w stdhttp.ResponseWriter) error
- func (c Cookie[V]) Encrypted(encrypter CookieEncrypter) EncryptedCookie[V]
- func (c Cookie[V]) GoString() string
- func (c Cookie[V]) Name() CookieName
- func (c Cookie[V]) Options() CookieOptions
- func (c Cookie[V]) Read(r *stdhttp.Request) (value.Optional[V], error)
- func (c Cookie[V]) Set(ctx context.Context, w stdhttp.ResponseWriter, v V) error
- func (c Cookie[V]) Signed(signer CookieSigner) SignedCookie[V]
- func (c Cookie[V]) String() string
- func (c Cookie[V]) Validate() error
- type CookieCodec
- func Base64Cookie[V any](codec CookieCodec[V]) CookieCodec[V]
- func BoolCookie[V ~bool]() CookieCodec[V]
- func FloatCookie[V PathFloat]() CookieCodec[V]
- func IntegerCookie[V PathInteger]() CookieCodec[V]
- func ModelIDCookie[M any]() CookieCodec[model.ID[M]]
- func SecretCookie() CookieCodec[secret.String]
- func StringCookie[V ~string]() CookieCodec[V]
- func TextCookie[V any, P PathTextPointer[V]]() CookieCodec[V]
- type CookieEncrypter
- type CookieName
- type CookieOptions
- type CookieSigner
- type CredentialInfo
- type CredentialKind
- type CredentialSource
- type CrossOriginEmbedderPolicy
- type CrossOriginOpenerPolicy
- type CrossOriginResourcePolicy
- type Disposition
- type Download
- func (Download) MarshalJSON() ([]byte, error)
- func (d Download) Validate() error
- func (d Download) WithDisposition(disposition Disposition) Download
- func (d Download) WithEntityTag(tag EntityTag) Download
- func (d Download) WithMediaType(media MediaType) Download
- func (d Download) WithName(name string) Download
- type DownloadContent
- type DownloadSource
- type ETagConfig
- type EncryptedCookie
- func (c EncryptedCookie[V]) Clear(w stdhttp.ResponseWriter) error
- func (c EncryptedCookie[V]) GoString() string
- func (c EncryptedCookie[V]) Name() CookieName
- func (c EncryptedCookie[V]) Options() CookieOptions
- func (c EncryptedCookie[V]) Read(r *stdhttp.Request) (value.Optional[V], error)
- func (c EncryptedCookie[V]) Set(ctx context.Context, w stdhttp.ResponseWriter, v V) error
- func (c EncryptedCookie[V]) String() string
- func (c EncryptedCookie[V]) Validate() error
- type Endpoint
- func AuthorizeEndpoint[P, Q, B, R any](e Endpoint[P, Q, B, R], authorize RequestAuthorization[P, Q, B]) Endpoint[P, Q, B, R]
- func BodyExample[P, Q, B, R any](e Endpoint[P, Q, B, R], body B) Endpoint[P, Q, B, R]
- func ConfigureEndpoint[P, Q, B, R any](endpoint Endpoint[P, Q, B, R], options ...EndpointOption) Endpoint[P, Q, B, R]
- func DefineEndpoint[P, Q, B, R any](route Route[P], query Query[Q], body Body[B], response Response[R], ...) Endpoint[P, Q, B, R]
- func EndpointHeaders[P, Q, B, R any](e Endpoint[P, Q, B, R], prepare ResponseHeaders[R]) Endpoint[P, Q, B, R]
- func PrepareEndpoint[P, Q, B, R any](e Endpoint[P, Q, B, R], prepare Preparation[P, Q, B]) Endpoint[P, Q, B, R]
- func ResponseExample[P, Q, B, R any](e Endpoint[P, Q, B, R], response R) Endpoint[P, Q, B, R]
- func ValidateBody[P, Q, B, R any](e Endpoint[P, Q, B, R], rules ...validation.Rule[B]) Endpoint[P, Q, B, R]
- func ValidateInput[P, Q, B, R any](e Endpoint[P, Q, B, R], rules ...validation.Rule[Input[P, Q, B]]) Endpoint[P, Q, B, R]
- func ValidatePath[P, Q, B, R any](e Endpoint[P, Q, B, R], rules ...validation.Rule[P]) Endpoint[P, Q, B, R]
- func ValidateQuery[P, Q, B, R any](e Endpoint[P, Q, B, R], rules ...validation.Rule[Q]) Endpoint[P, Q, B, R]
- type EndpointInfo
- func InspectAuthenticated[P, Q, B, M, R any](e AuthenticatedEndpoint[P, Q, B, M, R]) (EndpointInfo, error)
- func InspectAuthenticatedIdempotent[P, Q, B, M, R any](e AuthenticatedIdempotentEndpoint[P, Q, B, M, R]) (EndpointInfo, error)
- func InspectEndpoint[P, Q, B, R any](e Endpoint[P, Q, B, R]) (EndpointInfo, error)
- func InspectIdempotent[P, Q, B, R any](e IdempotentEndpoint[P, Q, B, R]) (EndpointInfo, error)
- func InspectOptional[P, Q, B, M, R any](e OptionalAuthenticationEndpoint[P, Q, B, M, R]) (EndpointInfo, error)
- func InspectSigned[P, Q, B, R any](e SignedEndpoint[P, Q, B, R]) (EndpointInfo, error)
- func InspectSignedAuthenticated[P, Q, B, S, R any](e SignedAuthenticatedEndpoint[P, Q, B, S, R]) (EndpointInfo, error)
- func InspectTicketAuthenticated[P, Q, B, M, R any](e TicketEndpoint[P, Q, B, M, R]) (EndpointInfo, error)
- type EndpointLimits
- type EndpointOption
- type EntityTag
- type ErrorCode
- type ErrorDeclaration
- type ErrorDefinition
- type ErrorResponse
- type Event
- type EventSink
- type EventStreamConfig
- type Events
- type FileResponseInfo
- type FileResponseLimits
- type FramePolicy
- type GuardBinding
- type GuardOption
- type GzipLevel
- type HSTSPolicy
- type Handler
- type HandlerTransport
- type HeaderName
- type HeaderValue
- type IPRateLimitOptions
- type IdempotencyInfo
- type IdempotentEndpoint
- func Idempotent[P, Q, B, R any](endpoint Endpoint[P, Q, B, R], store *idempotency.Store, ...) IdempotentEndpoint[P, Q, B, R]
- func IdempotentHeaders[P, Q, B, R any](e IdempotentEndpoint[P, Q, B, R], ...) IdempotentEndpoint[P, Q, B, R]
- func IdempotentSigned[P, Q, B, R any](endpoint SignedEndpoint[P, Q, B, R], store *idempotency.Store, ...) IdempotentEndpoint[P, Q, B, R]
- type Input
- type LocaleNegotiation
- type MFAChallengeCredential
- type MFARecoveryRequest
- type MFATOTPRequest
- type MediaType
- type Method
- func AuthenticatedEndpointMethod[P, Q, B, M, R any](endpoint AuthenticatedEndpoint[P, Q, B, M, R]) Method
- func EndpointMethod[P, Q, B, R any](e Endpoint[P, Q, B, R]) Method
- func OptionalEndpointMethod[P, Q, B, M, R any](endpoint OptionalAuthenticationEndpoint[P, Q, B, M, R]) Method
- func RouteMethod[P any](r Route[P]) Method
- func SignedAuthenticatedEndpointMethod[P, Q, B, S, R any](e SignedAuthenticatedEndpoint[P, Q, B, S, R]) Method
- func SignedEndpointMethod[P, Q, B, R any](e SignedEndpoint[P, Q, B, R]) Method
- func SignedRouteMethod[P any](r SignedRoute[P]) Method
- type Middleware
- func CORS(config CORSConfig) Middleware
- func CSRF(config CSRFConfig) Middleware
- func CacheControl(policy CachePolicy) Middleware
- func Compression(config CompressionConfig) Middleware
- func ContentSecurityPolicy(config CSPConfig) Middleware
- func CredentialRequests() Middleware
- func DefineMiddleware(id MiddlewareID, construct func(stdhttp.Handler) (stdhttp.Handler, error)) Middleware
- func ETags(config ETagConfig) Middleware
- func Locale(catalog *i18n.Catalog) Middleware
- func LocaleWith(catalog *i18n.Catalog, negotiation LocaleNegotiation) Middleware
- func PublicURLs(config PublicURLConfig) Middleware
- func RateLimit[K any](limiter ratelimit.Limiter[K], key func(*stdhttp.Request) (K, error)) Middleware
- func RateLimitByActor[M model.Identifiable](limiter ratelimit.Limiter[ActorKey], guard auth.Guard[M]) Middleware
- func RateLimitByActorWith[M model.Identifiable](limiter ratelimit.Limiter[ActorKey], guard auth.Guard[M], ...) Middleware
- func RateLimitByIP(limiter ratelimit.Limiter[netip.Addr]) Middleware
- func RateLimitByIPWith(limiter ratelimit.Limiter[netip.Addr], options IPRateLimitOptions) Middleware
- func RequirePublicURLs() Middleware
- func SecurityHeaders(config SecurityHeadersConfig) Middleware
- func StatementDetector(detector *database.StatementDetector, logger *slog.Logger) Middleware
- func TrustedProxy(config TrustedProxyConfig) Middleware
- func VerifyWebhook[A any](verifier *webhook.Verifier[A]) Middleware
- type MiddlewareID
- type Multipart
- type MultipartError
- type MultipartInfo
- type MultipartKind
- type MultipartLimits
- type MultipartPart
- func FilePart[B any](name string, field func(*B) *UploadedFile) MultipartPart[B]
- func JSONPart[B, V any](name string, descriptor contract.JSON[V], field func(*B) *V) MultipartPart[B]
- func OptionalFilePart[B any](name string, field func(*B) *value.Optional[UploadedFile]) MultipartPart[B]
- func OptionalJSONPart[B, V any](name string, descriptor contract.JSON[V], field func(*B) *value.Optional[V]) MultipartPart[B]
- func RepeatedFilePart[B any, S ~[]UploadedFile](name string, field func(*B) *S) MultipartPart[B]
- func RepeatedJSONPart[B, V any, S ~[]V](name string, descriptor contract.JSON[V], field func(*B) *S) MultipartPart[B]
- func TextPart[B any](parameter QueryParameter[B]) MultipartPart[B]
- type MultipartPartInfo
- type NoBody
- type NoContent
- type NoPath
- type NoQuery
- type OptionalAuthenticationEndpoint
- func AuthorizeOptionalActor[P, Q, B, M, R any](e OptionalAuthenticationEndpoint[P, Q, B, M, R], ...) OptionalAuthenticationEndpoint[P, Q, B, M, R]
- func ConfigureOptional[P, Q, B, M, R any](endpoint OptionalAuthenticationEndpoint[P, Q, B, M, R], ...) OptionalAuthenticationEndpoint[P, Q, B, M, R]
- func OptionalAuthentication[P, Q, B, M, R any](endpoint Endpoint[P, Q, B, R], authentication *Authentication, ...) OptionalAuthenticationEndpoint[P, Q, B, M, R]
- func OptionallyAuthenticated[P, Q, B, M, R any](endpoint Endpoint[P, Q, B, R], binding GuardBinding[M], ...) OptionalAuthenticationEndpoint[P, Q, B, M, R]
- func PrepareOptional[P, Q, B, M, R any](e OptionalAuthenticationEndpoint[P, Q, B, M, R], prepare Preparation[P, Q, B]) OptionalAuthenticationEndpoint[P, Q, B, M, R]
- type OptionalAuthenticationRoute
- type Origin
- type OriginPattern
- type Path
- type PathCodec
- func BoolPath[V ~bool]() PathCodec[V]
- func DescribeURL[V any](codec PathCodec[V], description contract.Scalar[V]) PathCodec[V]
- func EnumPath[E enum.Scalar, P PathTextPointer[E]](descriptor enum.Descriptor[E]) PathCodec[E]
- func FloatPath[V PathFloat]() PathCodec[V]
- func IntegerPath[V PathInteger]() PathCodec[V]
- func ModelIDPath[M any]() PathCodec[model.ID[M]]
- func StringPath[V ~string]() PathCodec[V]
- func TextPath[V any, P PathTextPointer[V]]() PathCodec[V]
- func URLType[V any](id contract.TypeID, codec PathCodec[V]) PathCodec[V]
- type PathFloat
- type PathInteger
- type PathParameter
- type PathParameterInfo
- type PathTextPointer
- type PayloadInfo
- type PermissionDirective
- type PermissionFeature
- type Preparation
- type ProxyHeader
- type ProxyOriginHeader
- type PublicURLConfig
- type Query
- type QueryCodec
- func BoolQuery[V ~bool]() QueryCodec[V]
- func EnumQuery[E enum.Scalar, P QueryTextPointer[E]](descriptor enum.Descriptor[E]) QueryCodec[E]
- func FloatQuery[V QueryFloat]() QueryCodec[V]
- func IntegerQuery[V QueryInteger]() QueryCodec[V]
- func ModelIDQuery[M any]() QueryCodec[model.ID[M]]
- func StringQuery[V ~string]() QueryCodec[V]
- func TextQuery[V any, P QueryTextPointer[V]]() QueryCodec[V]
- type QueryError
- type QueryFloat
- type QueryInteger
- type QueryLimits
- type QueryParameter
- func DefaultQueryParam[Q, V any](name string, codec QueryCodec[V], defaultValue V, field func(*Q) *V) QueryParameter[Q]
- func OptionalQueryParam[Q, V any](name string, codec QueryCodec[V], field func(*Q) *value.Optional[V]) QueryParameter[Q]
- func QueryParam[Q, V any](name string, codec QueryCodec[V], field func(*Q) *V) QueryParameter[Q]
- func RepeatedQueryParam[Q, V any, S ~[]V](name string, codec QueryCodec[V], field func(*Q) *S) QueryParameter[Q]
- type QueryParameterInfo
- type QueryTextPointer
- type RawBody
- type RawBodyInfo
- type RawBodyLimits
- type RawHandler
- type Redirect
- type ReferrerPolicy
- type RefreshCookie
- type RefreshCookieInfo
- type RefreshCookieLogoutRequest
- type RefreshCredential
- type RefreshTokenRequest
- type RequestAuthorization
- type RequestEvent
- type RequestMetric
- type RequestMetrics
- type RequestMetricsSnapshot
- type RequestObserver
- type RequestObserverFunc
- type Response
- func ClearRefreshCookie[R any](cookie RefreshCookie, response Response[R]) Response[R]
- func DownloadResponse(media MediaType, additional ...MediaType) Response[Download]
- func EmptyResponse(status int) Response[NoContent]
- func EventStreamResponse[T any](descriptor contract.JSON[T]) Response[Events[T]]
- func JSONResponse[R any](status int, descriptor contract.JSON[R]) Response[R]
- func JSONResponses[R any](descriptor contract.JSON[R], status int, alternatives ...int) Response[Statused[R]]
- func MFAEnrollmentResponse[M any](status int, source clock.Clock) Response[mfa.Enrollment[M]]
- func MFARecoveryResponse[M any](status int) Response[mfa.RecoveryCodes[M]]
- func RedirectResponse(status int) Response[Redirect]
- func StreamResponse(media MediaType, additional ...MediaType) Response[Stream]
- func TicketResponse[M, K any](status int, source clock.Clock) Response[token.Ticket[M, K]]
- func TokenCookieResponse[M, K any](cookie RefreshCookie, status int, source clock.Clock) Response[token.Issued[M, K]]
- func TokenResponse[M, K any](status int, source clock.Clock) Response[token.Issued[M, K]]
- type ResponseHeader
- type ResponseHeaders
- type Route
- type RouteDocumentation
- type RouteID
- func AuthenticatedEndpointID[P, Q, B, M, R any](endpoint AuthenticatedEndpoint[P, Q, B, M, R]) RouteID
- func EndpointID[P, Q, B, R any](e Endpoint[P, Q, B, R]) RouteID
- func IdempotentEndpointID[P, Q, B, R any](e IdempotentEndpoint[P, Q, B, R]) RouteID
- func OptionalEndpointID[P, Q, B, M, R any](endpoint OptionalAuthenticationEndpoint[P, Q, B, M, R]) RouteID
- func RouteIDOf[P any](r Route[P]) RouteID
- func SignedAuthenticatedEndpointID[P, Q, B, S, R any](e SignedAuthenticatedEndpoint[P, Q, B, S, R]) RouteID
- func SignedEndpointID[P, Q, B, R any](e SignedEndpoint[P, Q, B, R]) RouteID
- func SignedRouteID[P any](r SignedRoute[P]) RouteID
- type RouteInfo
- func InspectAuthenticatedRoute[P, M any](r AuthenticatedRoute[P, M]) (RouteInfo, error)
- func InspectOptionalRoute[P, M any](r OptionalAuthenticationRoute[P, M]) (RouteInfo, error)
- func InspectSignedAuthenticatedRoute[P, S any](r SignedAuthenticatedRoute[P, S]) (RouteInfo, error)
- func MatchedRoute(ctx context.Context) (RouteInfo, bool)
- type RouteOption
- type RouteRegistration
- func HandleAuthenticatedBound[P, Q, B, M, R any](e AuthenticatedEndpoint[P, Q, B, M, R], ...) RouteRegistration
- func HandleAuthenticatedRaw[P, M any](r AuthenticatedRoute[P, M], ...) RouteRegistration
- func HandleBound[P, Q, B, R any](e Endpoint[P, Q, B, R], bind Binding[P, Q, B, R]) RouteRegistration
- func HandleOptionalBound[P, Q, B, M, R any](e OptionalAuthenticationEndpoint[P, Q, B, M, R], ...) RouteRegistration
- func HandleOptionalRaw[P, M any](r OptionalAuthenticationRoute[P, M], ...) RouteRegistration
- func HandleRaw[P any](r Route[P], handler RawHandler[P]) RouteRegistration
- func HandleSignedAuthenticatedBound[P, Q, B, S, R any](e SignedAuthenticatedEndpoint[P, Q, B, S, R], ...) RouteRegistration
- func HandleSignedAuthenticatedRaw[P, S any](r SignedAuthenticatedRoute[P, S], ...) RouteRegistration
- func HandleSignedBound[P, Q, B, R any](e SignedEndpoint[P, Q, B, R], bind Binding[P, Q, B, R]) RouteRegistration
- func HandleSignedRaw[P any](r SignedRoute[P], handler RawHandler[P]) RouteRegistration
- func InvalidRouteRegistration(cause error) RouteRegistration
- func PrepareAuthenticatedIdempotent[P, Q, B, M, R any](e AuthenticatedIdempotentEndpoint[P, Q, B, M, R], ...) RouteRegistration
- func PrepareIdempotent[P, Q, B, R any](e IdempotentEndpoint[P, Q, B, R], prepare TransactionPreparation[P, Q, B, R]) RouteRegistration
- type RouteSpec
- type Router
- func (r *Router) Endpoints() []EndpointInfo
- func (r *Router) ErrorDefinitions() []ErrorDefinition
- func (r *Router) Routes() []RouteInfo
- func (r *Router) ServeHTTP(w stdhttp.ResponseWriter, request *stdhttp.Request)
- func (r *Router) WithFallback(id RouteID, handler stdhttp.Handler) (*Router, error)
- func (r *Router) WithSPA(id RouteID, assets *Assets, config SPAConfig) (*Router, error)
- type SPAConfig
- type Scope
- type SecurityHeadersConfig
- type SecurityRequestEvent
- type SecurityRequestObserver
- type Server
- type ServerConfig
- type ServerOption
- type SignedAuthenticatedEndpoint
- func ConfigureSignedAuthenticated[P, Q, B, S, R any](endpoint SignedAuthenticatedEndpoint[P, Q, B, S, R], options ...SignedOption) SignedAuthenticatedEndpoint[P, Q, B, S, R]
- func SignedAuthenticated[P, Q, B, M, R any](endpoint AuthenticatedEndpoint[P, Q, B, M, R], signer URLSigner) SignedAuthenticatedEndpoint[P, Q, B, M, R]
- func SignedOptionalAuthentication[P, Q, B, M, R any](endpoint OptionalAuthenticationEndpoint[P, Q, B, M, R], signer URLSigner) SignedAuthenticatedEndpoint[P, Q, B, value.Optional[M], R]
- type SignedAuthenticatedRoute
- func ConfigureSignedAuthenticatedRoute[P, S any](route SignedAuthenticatedRoute[P, S], options ...SignedOption) SignedAuthenticatedRoute[P, S]
- func SignAuthenticatedRoute[P, M any](r AuthenticatedRoute[P, M], signer URLSigner) SignedAuthenticatedRoute[P, M]
- func SignOptionalRoute[P, M any](r OptionalAuthenticationRoute[P, M], signer URLSigner) SignedAuthenticatedRoute[P, value.Optional[M]]
- type SignedCookie
- func (c SignedCookie[V]) Clear(w stdhttp.ResponseWriter) error
- func (c SignedCookie[V]) GoString() string
- func (c SignedCookie[V]) Name() CookieName
- func (c SignedCookie[V]) Options() CookieOptions
- func (c SignedCookie[V]) Read(r *stdhttp.Request) (value.Optional[V], error)
- func (c SignedCookie[V]) Set(ctx context.Context, w stdhttp.ResponseWriter, v V) error
- func (c SignedCookie[V]) String() string
- func (c SignedCookie[V]) Validate() error
- type SignedEndpoint
- type SignedOption
- type SignedRoute
- type SignedURLInfo
- type SigningKey
- type SigningKeyID
- type SigningKeys
- type Statused
- type Stream
- type StreamContent
- type StreamSource
- type TicketEndpoint
- type TransactionHandler
- type TransactionPreparation
- type TrustedProxyConfig
- type URLScalarInfo
- type URLSigner
- type URLSyntax
- type UploadedFile
Constants ¶
const ( DefaultResponseBytes = 32 << 20 DefaultResponseNodes = 1 << 20 )
DefaultResponseBytes and DefaultResponseNodes bound a typed JSON response by default: large enough for ordinary list pages (tens of thousands of rows), still bounded. Nodes count values and object names; Steps allow four visits per node.
const ( MaxRouteSummaryBytes = 256 MaxRouteDescriptionBytes = 16 << 10 MaxRouteTags = 16 MaxRouteTagBytes = 64 )
Documentation bounds. Summary and tags are single lines; a description may contain line breaks and tabs.
const ErrInvalidEncryptedCookie cookieEncryptionError = "invalid encrypted cookie"
ErrInvalidEncryptedCookie identifies malformed, tampered, expired, rescoped or retired-key encrypted cookies through errors.Is. Transport reads wrap it as a shared BadRequest.
const ErrInvalidSignedCookie cookieSignatureError = "invalid signed cookie"
ErrInvalidSignedCookie identifies malformed, tampered, expired or retired-key cookies through errors.Is. Transport reads wrap it as a shared BadRequest.
const ErrInvalidSignedURL signedURLError = "invalid signed URL"
ErrInvalidSignedURL identifies malformed, changed, expired or retired-key links through errors.Is. Registered signed routes return the shared 403.
const EventStreamMediaType = "text/event-stream"
EventStreamMediaType is the media type of server-sent event responses.
const MaxCookieBytes = 4096
MaxCookieBytes bounds a complete outgoing Set-Cookie field, including scope.
const MaxExampleBytes = 64 << 10
MaxExampleBytes bounds one encoded request or response example.
const MaxHeaderValueBytes = 8192
const MaxRouteBodyBytes int64 = 1 << 40
MaxRouteBodyBytes bounds a declared per-route request-body ceiling.
const MaxRouteTimeout = 24 * time.Hour
MaxRouteTimeout bounds a declared per-route request deadline. It is the framework's safety ceiling for long uploads, downloads and event streams.
const MaxSecurityPathBytes = 512
const MaxSignedURLBytes = 64 << 10
MaxSignedURLBytes bounds the complete absolute URL, including its envelope.
const MaxSignedURLQueryPairs = 1024
MaxSignedURLQueryPairs includes the two framework-owned signing parameters.
const RequestIDHeader = "X-Request-ID"
Variables ¶
var ( IdempotencyBadKey = DefineError("idempotency_bad_key", 400, "A valid idempotency key is required.") IdempotencyMismatch = DefineError("idempotency_mismatch", 409, "This key belongs to a different submission.") IdempotencyInProgress = DefineError("idempotency_in_progress", 409, "This submission is still in progress. Retry with the same key.") IdempotencyCapacity = DefineError("idempotency_capacity", 429, "Idempotency admission capacity is unavailable.") )
Functions ¶
func AbsoluteURL ¶
AbsoluteURL accepts an origin-relative path/query and an explicit HTTP(S) origin. Absolute/network-path URLs, fragments, backslashes, control bytes and invalid escaping are rejected. Existing route path/query escaping is preserved.
func ApplyMiddleware ¶
ApplyMiddleware constructs a chain in declaration order: the first item is outermost on the request and last on the response. Constructors run inside-out once; no request is started here. Apply this around a Router for global policy, including redirects, missing routes and method errors. Route inspection lists only route/scope middleware; it does not infer wrappers outside the router. The original native ResponseWriter is preserved unless a supplied wrapper explicitly replaces it. Optional writer capabilities remain its responsibility.
func AssetsModule ¶
func AssetsModule(name foundation.ProviderID, key foundation.Key[*Assets], config AssetsConfig) foundation.Module
AssetsModule prepares a source during Build, opens its directory during Boot and closes it after managed kernels/requests exit. Consumers declare the source and resolve *Assets while assembling routes; they do not manage os.Root.
func AuthenticatedEndpointPattern ¶ added in v0.2.0
func AuthenticatedEndpointPattern[P, Q, B, M, R any](endpoint AuthenticatedEndpoint[P, Q, B, M, R]) string
AuthenticatedEndpointPattern returns the endpoint's path template.
func AuthenticatedRouteURL ¶ added in v0.2.0
func AuthenticatedRouteURL[P, M any](r AuthenticatedRoute[P, M], path P) (string, error)
AuthenticatedRouteURL validates the authenticated declaration and formats its typed path.
func ClientIP ¶
ClientIP returns the IP captured in shared request attribution. The HTTP kernel starts with the socket peer; TrustedProxy may replace it after checking the peer and chain. Outside attributed work it returns an invalid address.
func DecodeQuery ¶ added in v0.2.0
DecodeQuery rejects unknown names, duplicate scalar values, missing required fields and malformed wire input before invoking any codec. Repeated values retain their order. No body or path values are merged into the query.
Codec and field-selector execution is owned until it returns, even after cancellation. It runs on the caller's goroutine: panics become internal failures, and runtime.Goexit ends the goroutine as any Go call does. Custom codecs must be deterministic and concurrency-safe and must not retain input references that they can mutate. Every failure discards the partially constructed Q.
func EncodeQuery ¶ added in v0.2.0
func EncodeQuery[Q any](d Query[Q], ctx context.Context, input Q, limits QueryLimits) (string, error)
EncodeQuery produces a relative query without a question mark. Nil and empty slices are omitted; Optional zero values are omitted. Parameter and value types remain concrete at the call site. Query escaping is applied exactly once by the shared wire layer. The caller must keep input unchanged until return; custom formatters own their internal work and allocation.
func EndpointPattern ¶ added in v0.2.0
EndpointPattern returns the endpoint's path template.
func ErrorResponseJSON ¶
func ErrorResponseJSON() contract.JSON[ErrorResponse]
ErrorResponseJSON describes the actual shared failure envelope. Its fields and tags remain owned by ErrorResponse and contract.Issue; exporters obtain status/code membership separately from the router's error definitions.
func IsHTMLNavigation ¶
IsHTMLNavigation reports whether r is a GET/HEAD navigation to an extensionless asset name whose bounded Accept header permits text/html (q > 0). name is relative to the asset source, and may end with a directory slash.
func IsSecure ¶
IsSecure reports the validated public request scheme when TrustedProxy has supplied one, otherwise native TLS. A configured URL base and arbitrary headers never make a request secure. Run TrustedProxy before security/cookie policy.
func LastEventID ¶
LastEventID returns the Last-Event-ID a reconnecting client sent to a typed event stream endpoint, so its producer can resume after that event. A missing, repeated or invalid header (over 1 KiB, invalid UTF-8, NUL or line breaks) is absent.
func MessageDefinitions ¶
func MessageDefinitions() []i18n.MessageDefinition
MessageDefinitions returns the parameter-free signatures for shared HTTP error envelopes (http.error.<code>) and decoding issues (http.input.<code>). Configured applications register these automatically when locales are enabled.
func Module ¶
func Module(name foundation.ProviderID, key foundation.Key[*Server], config ServerConfig, construct func(foundation.Resolver) (stdhttp.Handler, error), options ...ServerOption) foundation.Module
Module registers one prepared server and the HTTP kernel. The handler factory runs once per application during Build and may resolve explicit dependencies; it must not start I/O or goroutines. Only App.Run with foundation.HTTP binds the listener, after all providers boot. Other kernels can share this assembly. The application supplies its logger and retains services until handlers exit.
func OptionalEndpointPattern ¶ added in v0.2.0
func OptionalEndpointPattern[P, Q, B, M, R any](endpoint OptionalAuthenticationEndpoint[P, Q, B, M, R]) string
OptionalEndpointPattern returns the endpoint's path template.
func OptionalRouteURL ¶ added in v0.2.0
func OptionalRouteURL[P, M any](r OptionalAuthenticationRoute[P, M], path P) (string, error)
OptionalRouteURL validates the optional-authentication declaration and formats its typed path.
func PathPattern ¶ added in v0.2.0
PathPattern returns the declared path template.
func PathURL ¶ added in v0.2.0
PathURL renders a relative path, escaping each value once. No incoming host or forwarded header participates. The concrete P prevents unrelated model IDs or path DTOs from being supplied to this route. Codec and selector callbacks run on the caller's goroutine; a panic becomes an internal failure. Custom codec errors remain private causes without invoking their error methods.
func PeerIP ¶
PeerIP parses the native socket peer without trusting any request header. IPv4-mapped addresses are unmapped and local interface zones are removed. A missing or non-IP peer returns an invalid address, never a trusted fallback.
func PermanentAuthenticatedEndpointURL ¶ added in v0.2.0
func PermanentAuthenticatedEndpointURL[P, Q, B, S, R any](e SignedAuthenticatedEndpoint[P, Q, B, S, R], ctx context.Context, origin Origin, path P, query Q) (string, error)
PermanentAuthenticatedEndpointURL signs an origin-bound link without expiry; the endpoint must permit permanent links.
func PermanentAuthenticatedRouteURL ¶ added in v0.2.0
func PermanentAuthenticatedRouteURL[P, S any](r SignedAuthenticatedRoute[P, S], ctx context.Context, origin Origin, path P) (string, error)
PermanentAuthenticatedRouteURL signs an origin-bound raw-route link without expiry; the route must permit permanent links.
func PermanentEndpointURL ¶ added in v0.2.0
func PermanentEndpointURL[P, Q, B, R any](e SignedEndpoint[P, Q, B, R], ctx context.Context, origin Origin, path P, query Q) (string, error)
PermanentEndpointURL signs a link without expiry; the endpoint must opt in.
func PermanentRouteURL ¶ added in v0.2.0
func PermanentRouteURL[P any](r SignedRoute[P], ctx context.Context, origin Origin, path P) (string, error)
PermanentRouteURL signs a link without expiry; the route must opt in with WithPermanentLinks. Origin binding and every other rule are unchanged.
func PublicURL ¶
PublicURL combines the request's approved origin with a relative URL returned by a typed route or endpoint. Background kernels use AbsoluteURL with an explicitly configured Origin. No request Host or environment global is inferred.
func RateLimitExceeded ¶
RateLimitExceeded converts a denied decision from a handler-level limiter call into the shared 429 error. WriteError then sends Retry-After and the X-RateLimit-* headers from the decision. An allowed or invalid decision is an internal error: it must never be reported as a quota rejection.
func RegisterEndpoint ¶ added in v0.2.0
func RegisterEndpoint[P, Q, B, R any](r *foundation.Registrar, key foundation.Key[*Router], declaration Endpoint[P, Q, B, R], construct func(foundation.Resolver) (RouteRegistration, error)) error
RegisterEndpoint registers the concrete declaration and validates the factory's transport contract.
func RegisterIdempotentEndpoint ¶ added in v0.2.0
func RegisterIdempotentEndpoint[P, Q, B, R any](r *foundation.Registrar, key foundation.Key[*Router], declaration IdempotentEndpoint[P, Q, B, R], construct func(foundation.Resolver) (RouteRegistration, error)) error
RegisterIdempotentEndpoint registers the concrete declaration and validates the factory's transport contract.
func RegisterMiddleware ¶
func RegisterMiddleware(r *foundation.Registrar, key foundation.Key[*Router], middleware Middleware) error
RegisterMiddleware adds outer middleware to each contributed route in this router, retaining its identity in route/endpoint inspection. Native unmatched redirects and 404/405 responses do not acquire a fabricated route identity.
func RegisterRoute ¶
func RegisterRoute[P any](r *foundation.Registrar, key foundation.Key[*Router], declaration Route[P], construct func(foundation.Resolver) (RouteRegistration, error)) error
RegisterRoute registers the concrete declaration and validates the factory's transport contract.
func RegisterRouter ¶
func RegisterRouter(r *foundation.Registrar, key foundation.Key[*Router]) error
RegisterRouter assembles all contributions through the existing native router. An application may register this in its HTTP provider and resolve it from the HTTP Module handler factory. Assembly performs no network I/O.
func RegisterRouterWithRoutes ¶
func RegisterRouterWithRoutes(r *foundation.Registrar, key foundation.Key[*Router], construct func(foundation.Resolver) ([]RouteRegistration, error)) error
RegisterRouterWithRoutes combines ordinary typed handler registrations with provider/plugin contributions. Duplicate/ambiguous routes fail as one graph.
func RegisterSPA ¶
func RegisterSPA(r *foundation.Registrar, key foundation.Key[*Router], id RouteID, assets foundation.Key[*Assets], config SPAConfig) error
RegisterSPA adds a SPA fallback, as Router.WithSPA declares it, to the router assembled under key. The route ID and configuration are checked here; assets is resolved when that router is built, during Build and before any provider boots, so an unknown assets key or a duplicate route ID or prefix fails Build before resources open. Asset mounts with a less specific or equal prefix defer to the SPA as WithSPA describes.
func RegisterSignedEndpoint ¶ added in v0.2.0
func RegisterSignedEndpoint[P, Q, B, R any](r *foundation.Registrar, key foundation.Key[*Router], declaration SignedEndpoint[P, Q, B, R], construct func(foundation.Resolver) (RouteRegistration, error)) error
RegisterSignedEndpoint registers the concrete declaration and validates the factory's transport contract.
func RegisterSignedRoute ¶ added in v0.2.0
func RegisterSignedRoute[P any](r *foundation.Registrar, key foundation.Key[*Router], declaration SignedRoute[P], construct func(foundation.Resolver) (RouteRegistration, error)) error
RegisterSignedRoute registers the concrete declaration and validates the factory's transport contract.
func RelativeAuthenticatedEndpointURL ¶ added in v0.2.0
func RelativeAuthenticatedEndpointURL[P, Q, B, S, R any](e SignedAuthenticatedEndpoint[P, Q, B, S, R], ctx context.Context, path P, query Q, expires time.Time) (string, error)
RelativeAuthenticatedEndpointURL signs an expiring origin-relative link valid on every admitted origin.
func RelativeAuthenticatedRouteURL ¶ added in v0.2.0
func RelativeAuthenticatedRouteURL[P, S any](r SignedAuthenticatedRoute[P, S], ctx context.Context, path P, expires time.Time) (string, error)
RelativeAuthenticatedRouteURL signs an expiring origin-relative raw-route link valid on every admitted origin.
func RelativeEndpointURL ¶ added in v0.2.0
func RelativeEndpointURL[P, Q, B, R any](e SignedEndpoint[P, Q, B, R], ctx context.Context, path P, query Q, expires time.Time) (string, error)
RelativeEndpointURL signs an origin-relative link, valid on every admitted origin.
func RelativeRouteURL ¶ added in v0.2.0
func RelativeRouteURL[P any](r SignedRoute[P], ctx context.Context, path P, expires time.Time) (string, error)
RelativeRouteURL signs an origin-relative link. It is not bound to an origin, so it verifies on every origin PublicURLs admits for this route; use URL when a link must stay on one host or tenant.
func RequestID ¶
func RequestID(ctx context.Context) attribution.RequestID
RequestID returns the request's typed correlation ID from shared attribution. Outside a request/attributed operation it returns the empty ID. HTTP generates its own ID rather than trusting an incoming correlation header.
func RoutePattern ¶ added in v0.2.0
RoutePattern returns the route's path template.
func RouteURL ¶ added in v0.2.0
RouteURL generates this route's relative URL from its concrete path type. It validates the route identity and reuses the path grammar parsed once by DefinePath; middleware declarations do not affect URLs and are validated at registration.
func ServeEvents ¶
func ServeEvents[T any](w stdhttp.ResponseWriter, r *stdhttp.Request, descriptor contract.JSON[T], config EventStreamConfig, produce func(context.Context, *EventSink[T]) error) error
ServeEvents writes a server-sent event (text/event-stream) response from a raw route handler. It commits 200 with Cache-Control: no-store, then runs produce and writes each queued event as soon as possible, flushing per event and writing heartbeat comments while idle. HEAD receives the headers only and never runs produce. Compression and ETag middleware pass event streams through.
produce receives a context that ends when the request ends (client disconnect, forced shutdown or the route deadline) or the stream fails, and must return promptly then; ServeEvents waits for its actual return, including after cancellation, and contains its panics and Goexit. Declare the route's WithTimeout for the stream's longest lifetime: the kernel RequestTimeout and WriteTimeout otherwise end it. The client resumes with the Last-Event-ID request header, which the handler reads from the request.
It returns nil after produce returned nil and every accepted event was written. Otherwise it returns the first failure: produce's own error (after writing the events it already accepted), a contained producer panic as an internal error, an invalid or oversized event payload (the stream ends; no partial event is written), the request context's error, or a write failure. The response is committed by then, so the handler cannot send an error body.
func SignedAuthenticatedEndpointPattern ¶ added in v0.2.0
func SignedAuthenticatedEndpointPattern[P, Q, B, S, R any](e SignedAuthenticatedEndpoint[P, Q, B, S, R]) string
SignedAuthenticatedEndpointPattern returns the endpoint's path template.
func SignedAuthenticatedRouteURL ¶ added in v0.2.0
func SignedAuthenticatedRouteURL[P, S any](r SignedAuthenticatedRoute[P, S], ctx context.Context, origin Origin, path P, expires time.Time) (string, error)
SignedAuthenticatedRouteURL validates the declaration and signs an expiring origin-bound raw-route link.
func SignedEndpointPattern ¶ added in v0.2.0
func SignedEndpointPattern[P, Q, B, R any](e SignedEndpoint[P, Q, B, R]) string
SignedEndpointPattern returns the endpoint's path template.
func SignedRoutePattern ¶ added in v0.2.0
func SignedRoutePattern[P any](r SignedRoute[P]) string
SignedRoutePattern returns the underlying path template.
func SignedRouteURL ¶ added in v0.2.0
func SignedRouteURL[P any](r SignedRoute[P], ctx context.Context, origin Origin, path P, expires time.Time) (string, error)
SignedRouteURL uses an explicitly approved origin in background kernels. Request handlers can obtain one through PublicOrigin after PublicURLs middleware. Expiry is mandatory, measured in whole Unix seconds, and must be in the future.
func ValidateAuthenticated ¶ added in v0.2.0
func ValidateAuthenticated[P, Q, B, M, R any](e AuthenticatedEndpoint[P, Q, B, M, R]) error
ValidateAuthenticated checks the endpoint and its required authentication binding.
func ValidateAuthenticatedIdempotent ¶ added in v0.2.0
func ValidateAuthenticatedIdempotent[P, Q, B, M, R any](e AuthenticatedIdempotentEndpoint[P, Q, B, M, R]) error
ValidateAuthenticatedIdempotent checks the authenticated source and idempotent endpoint declaration.
func ValidateAuthenticatedRoute ¶ added in v0.2.0
func ValidateAuthenticatedRoute[P, M any](r AuthenticatedRoute[P, M]) error
ValidateAuthenticatedRoute checks the raw route and required authentication binding.
func ValidateBodyDescriptor ¶ added in v0.2.0
ValidateBodyDescriptor checks that the request body has a reader and a valid descriptor.
func ValidateEndpoint ¶ added in v0.2.0
ValidateEndpoint checks declarations, lifecycle callbacks, limits, error and header contracts, and method-specific body and credential restrictions.
func ValidateIdempotent ¶ added in v0.2.0
func ValidateIdempotent[P, Q, B, R any](e IdempotentEndpoint[P, Q, B, R]) error
ValidateIdempotent checks the operation, store and endpoint, requiring replayable middleware and supported noncredential input and response contracts.
func ValidateMultipart ¶ added in v0.2.0
ValidateMultipart checks retained descriptor errors, upload indexes, the server temporary directory and text-field declaration.
func ValidateOptional ¶ added in v0.2.0
func ValidateOptional[P, Q, B, M, R any](e OptionalAuthenticationEndpoint[P, Q, B, M, R]) error
ValidateOptional checks the endpoint, optional authentication binding and any authorization callback.
func ValidateOptionalRoute ¶ added in v0.2.0
func ValidateOptionalRoute[P, M any](r OptionalAuthenticationRoute[P, M]) error
ValidateOptionalRoute checks the raw route and optional authentication binding.
func ValidateQueryDescriptor ¶ added in v0.2.0
ValidateQueryDescriptor checks immutable binding declarations without calling user methods.
func ValidateResponse ¶ added in v0.2.0
ValidateResponse checks the response kind, status, codecs and associated file, event or refresh-cookie contracts.
func ValidateRoute ¶ added in v0.2.0
ValidateRoute checks the declaration without starting I/O or running a handler.
func ValidateSigned ¶ added in v0.2.0
func ValidateSigned[P, Q, B, R any](e SignedEndpoint[P, Q, B, R]) error
ValidateSigned checks the endpoint and signer and rejects query fields colliding with signing or ignored parameters.
func ValidateSignedAuthenticated ¶ added in v0.2.0
func ValidateSignedAuthenticated[P, Q, B, S, R any](e SignedAuthenticatedEndpoint[P, Q, B, S, R]) error
ValidateSignedAuthenticated checks the authentication transport and signed endpoint declaration.
func ValidateSignedAuthenticatedRoute ¶ added in v0.2.0
func ValidateSignedAuthenticatedRoute[P, S any](r SignedAuthenticatedRoute[P, S]) error
ValidateSignedAuthenticatedRoute checks the authentication transport, raw route and signer.
func ValidateSignedRoute ¶ added in v0.2.0
func ValidateSignedRoute[P any](r SignedRoute[P]) error
ValidateSignedRoute checks the route and signer and rejects TRACE routes.
func ValidateTicketAuthenticated ¶ added in v0.4.0
func ValidateTicketAuthenticated[P, Q, B, M, R any](e TicketEndpoint[P, Q, B, M, R]) error
ValidateTicketAuthenticated checks the complete declaration, retaining any construction failure before a route can register or generate a URL.
func WriteError ¶
WriteError sends the shared JSON error envelope to a fresh response. Call it before writing status/body; a response already sent cannot be replaced. Nil errors are rejected. Internal causes are retained by their originating error, never exposed in JSON. Raw handlers may use this explicit transport adapter. Classification contains custom error methods; panic or Goexit becomes a safe internal response before headers or body are written. A failed retry lookup retains the selected response and omits its hint. Error methods must terminate and be safe for concurrent classification calls. Each search is bounded to 256 nodes and 64 nested levels; exhausted classification becomes InternalError, while an exhausted retry lookup omits Retry-After.
Types ¶
type Access ¶
type Access string
Access describes an explicitly selected route access contract. An unknown or omitted access value cannot silently create a public route.
type ActorKey ¶
type ActorKey string
ActorKey is a bounded quota key: a digest of the authenticated model identity, or the masked client network for anonymous requests. Declare actor limiters with ActorKeys().
type ActorOption ¶ added in v0.2.0
type ActorOption[M any] interface { GuardOption[M] // contains filtered or unexported methods }
ActorOption is the middleware-only subset accepted by optional authentication.
func ActorMiddleware ¶ added in v0.2.0
func ActorMiddleware[M any](middleware ...Middleware) ActorOption[M]
ActorMiddleware snapshots middleware to run with the resolved authentication actor.
type AssetExtension ¶
type AssetExtension string
AssetExtension is a lowercase suffix including its leading dot, such as .css.
type AssetMount ¶
type AssetMount struct {
// contains filtered or unexported fields
}
AssetMount declares one named GET/HEAD subtree. Register contributes it to NewRouter; URL encodes an AssetPath through the same prefix declaration.
func (AssetMount) Register ¶
func (m AssetMount) Register() RouteRegistration
Register creates the asset route registration, retaining validation errors and coordinating missing-asset fallback with mounted SPAs.
func (AssetMount) URL ¶
func (m AssetMount) URL(name AssetPath) (string, error)
URL formats an asset path under the mount, preserving a valid directory trailing slash.
func (AssetMount) Validate ¶
func (m AssetMount) Validate() error
Validate requires constructed assets and a valid route declaration.
func (AssetMount) WithMiddleware ¶
func (m AssetMount) WithMiddleware(middleware ...Middleware) AssetMount
WithMiddleware returns a mount with the supplied middleware appended to its route.
func (AssetMount) WithNavigationFallback ¶
func (m AssetMount) WithNavigationFallback(handler stdhttp.Handler) AssetMount
WithNavigationFallback returns a mount that delegates missing HTML navigations to handler inside its middleware. A nil handler disables the fallback. Routes and covering SPAs retain precedence; the handler owns its response headers.
type AssetPath ¶
type AssetPath string
AssetPath is a relative slash-separated asset path. Empty identifies a mount root; one trailing slash identifies a directory. Download requires a file path.
type AssetRouteInfo ¶
type AssetRouteInfo struct {
Prefix string `json:"prefix"`
Index AssetPath `json:"index,omitempty"`
File FileResponseInfo `json:"file"`
Fallback bool `json:"fallback"`
Excluded []string `json:"excluded,omitempty"`
}
AssetRouteInfo describes a framework file boundary without inventing a JSON DTO. It never exposes a local directory or a filesystem implementation.
type AssetSource ¶
type AssetSource struct {
// contains filtered or unexported fields
}
AssetSource is a declared local directory or caller-owned filesystem. The zero value is invalid. Construct it with DirectoryAssets or FilesystemAssets.
func DirectoryAssets ¶
func DirectoryAssets(directory string) AssetSource
DirectoryAssets declares a directory source to open when assets start.
func FilesystemAssets ¶
func FilesystemAssets(fsys fs.FS) AssetSource
FilesystemAssets supports embed.FS and other concurrency-safe filesystems. The caller owns fsys; Foundry closes individual files. Only DirectoryAssets promises os.Root confinement. Files must implement io.ReadSeekCloser.
type Assets ¶
type Assets struct {
// contains filtered or unexported fields
}
Assets owns a prepared asset source. Directory handles stay open until all acquired file bodies and lookup operations have finished. Close stops new acquisitions, waits for existing owners and never interrupts a file read. AssetsModule owns this lifecycle in applications; OpenAssets is for explicit standalone use and tests. Assets must not be copied after construction.
func OpenAssets ¶
func OpenAssets(ctx context.Context, config AssetsConfig) (*Assets, error)
OpenAssets validates and opens the configured asset source. The caller must close the returned assets.
func (*Assets) Close ¶
Close is idempotent. A canceled wait does not reopen the source or abandon its handles: the final owner completes closure and later Close calls observe it.
type AssetsConfig ¶
type AssetsConfig struct {
Source AssetSource
Index AssetPath
Media map[AssetExtension]MediaType
CacheControl HeaderValue
Limits FileResponseLimits
AllowHidden bool
}
AssetsConfig owns source, index, media and transfer policies. Start with DefaultAssetsConfig. Constructors snapshot Media; unknown suffixes use application/octet-stream, without consulting host MIME files or global state.
func DefaultAssetsConfig ¶
func DefaultAssetsConfig(source AssetSource) AssetsConfig
DefaultAssetsConfig returns an index.html policy with no-cache headers, default file limits and common media types.
func (AssetsConfig) Validate ¶
func (c AssetsConfig) Validate() error
Validate checks the source, response limits, cache headers, index policy and bounded media-type declarations.
type AuthenticatedBinding ¶
type AuthenticatedBinding[P, Q, B, S, R any] func(context.Context, S, Input[P, Q, B]) (func(context.Context, S, Input[P, Q, B]) (R, error), error)
AuthenticatedBinding is the binding stage of an authenticated endpoint: it receives the concrete subject after request authorization and before validation and returns the handler completing the request (see Binding).
type AuthenticatedBindingTransport ¶ added in v0.2.0
type AuthenticatedBindingTransport[P, Q, B, S, R any] struct { // contains filtered or unexported fields }
AuthenticatedBindingTransport exposes the explicit pre-validation binding stage.
func AfterAuthenticatedValidation ¶ added in v0.2.0
func AfterAuthenticatedValidation[P, Q, B, S, R any](transport AuthenticatedHandlerTransport[P, Q, B, S, R]) AuthenticatedBindingTransport[P, Q, B, S, R]
AfterAuthenticatedValidation adapts a handler transport to run binding after its validation and authentication stages.
func ForAuthenticatedBinding ¶ added in v0.2.0
func ForAuthenticatedBinding[P, Q, B, S, R any](endpoint AuthenticatedEndpoint[P, Q, B, S, R]) AuthenticatedBindingTransport[P, Q, B, S, R]
ForAuthenticatedBinding exposes the endpoint's authenticated binding stage while preserving its concrete types.
func ForOptionalBinding ¶ added in v0.2.0
func ForOptionalBinding[P, Q, B, S, R any](endpoint OptionalAuthenticationEndpoint[P, Q, B, S, R]) AuthenticatedBindingTransport[P, Q, B, value.Optional[S], R]
ForOptionalBinding exposes the optional-authentication endpoint's binding stage with an optional concrete subject.
func ForSignedAuthenticatedBinding ¶ added in v0.2.0
func ForSignedAuthenticatedBinding[P, Q, B, S, R any](endpoint SignedAuthenticatedEndpoint[P, Q, B, S, R]) AuthenticatedBindingTransport[P, Q, B, S, R]
ForSignedAuthenticatedBinding exposes the signed authenticated endpoint's binding stage.
func ForSignedOptionalBinding ¶ added in v0.2.0
func ForSignedOptionalBinding[P, Q, B, S, R any](endpoint SignedAuthenticatedEndpoint[P, Q, B, value.Optional[S], R]) AuthenticatedBindingTransport[P, Q, B, value.Optional[S], R]
ForSignedOptionalBinding exposes the signed optional-subject endpoint's binding stage.
func (AuthenticatedBindingTransport[P, Q, B, S, R]) Description ¶ added in v0.2.0
func (t AuthenticatedBindingTransport[P, Q, B, S, R]) Description() (EndpointInfo, error)
Description validates the binding transport and returns its endpoint metadata.
func (AuthenticatedBindingTransport[P, Q, B, S, R]) HandleBound ¶ added in v0.2.0
func (t AuthenticatedBindingTransport[P, Q, B, S, R]) HandleBound(bind AuthenticatedBinding[P, Q, B, S, R]) RouteRegistration
HandleBound registers the authenticated binding, retaining invalid transport or nil-binding errors in the registration.
func (AuthenticatedBindingTransport[P, Q, B, S, R]) Validate ¶ added in v0.2.0
func (t AuthenticatedBindingTransport[P, Q, B, S, R]) Validate() error
Validate checks the adapter callbacks and underlying transport; a zero transport is invalid.
type AuthenticatedEndpoint ¶
type AuthenticatedEndpoint[P, Q, B, M, R any] struct { // contains filtered or unexported fields }
AuthenticatedEndpoint preserves DTO contracts and supplies a concrete model only after its guard succeeds. Model fields never become response DTOs.
func Authenticated ¶
func Authenticated[P, Q, B, M, R any](endpoint Endpoint[P, Q, B, R], binding GuardBinding[M], options ...GuardOption[M]) AuthenticatedEndpoint[P, Q, B, M, R]
Authenticated requires the bound guard's concrete subject and applies guard options to endpoint.
func AuthorizeActor ¶ added in v0.2.0
func AuthorizeActor[P, Q, B, M, R any](e AuthenticatedEndpoint[P, Q, B, M, R], authorize func(context.Context, M, Input[P, Q, B]) error) AuthenticatedEndpoint[P, Q, B, M, R]
AuthorizeActor receives the selected guard's concrete actor and the prepared request before validation and domain/resource work, so a denied actor never reaches database-backed rules. Configure this before Signed or binding.
func ConfigureAuthenticated ¶ added in v0.2.0
func ConfigureAuthenticated[P, Q, B, M, R any](endpoint AuthenticatedEndpoint[P, Q, B, M, R], options ...GuardOption[M]) AuthenticatedEndpoint[P, Q, B, M, R]
ConfigureAuthenticated applies guard options to a copy of endpoint, retaining missing-option errors for validation.
func PrepareAuthenticated ¶ added in v0.2.0
func PrepareAuthenticated[P, Q, B, M, R any](e AuthenticatedEndpoint[P, Q, B, M, R], prepare Preparation[P, Q, B]) AuthenticatedEndpoint[P, Q, B, M, R]
PrepareAuthenticated configures the same typed preparation stage after credential admission and structural decoding. Authentication itself is never rerun here.
func RequireAuthentication ¶
func RequireAuthentication[P, Q, B, M, R any](endpoint Endpoint[P, Q, B, R], authentication *Authentication, guard auth.Guard[M], options ...GuardOption[M]) AuthenticatedEndpoint[P, Q, B, M, R]
RequireAuthentication binds a Guarded transport declaration. Authentication runs before parameter/body decoding; its model is reused by the handler and policies within this request. Verified identity is attached to shared attribution before decoding, preserving request metadata. An unbound Guarded endpoint cannot register.
func (AuthenticatedEndpoint[P, Q, B, M, R]) Handle ¶
func (e AuthenticatedEndpoint[P, Q, B, M, R]) Handle(handler func(context.Context, M, Input[P, Q, B]) (R, error)) RouteRegistration
Handle registers a typed callback requiring the guard's current concrete subject.
type AuthenticatedHandlerTransport ¶ added in v0.2.0
type AuthenticatedHandlerTransport[P, Q, B, S, R any] interface { // Validate checks the authenticated transport declaration. Validate() error // Description returns the authenticated endpoint's contract metadata. Description() (EndpointInfo, error) // Handle registers a callback receiving the concrete authenticated subject and typed // input. Handle(func(context.Context, S, Input[P, Q, B]) (R, error)) RouteRegistration }
AuthenticatedHandlerTransport composes the request/response contract with its concrete handler subject S. Required adapters use their model; optional adapters use value.Optional[Model]. Model-binding adapters preserve this distinction. A custom implementation owns its authentication semantics; this interface alone is not an authentication capability.
type AuthenticatedIdempotentEndpoint ¶
type AuthenticatedIdempotentEndpoint[P, Q, B, M, R any] struct { // contains filtered or unexported fields }
AuthenticatedIdempotentEndpoint preserves the authenticated source alongside its typed idempotency operation.
func AuthenticatedIdempotentHeaders ¶ added in v0.2.0
func AuthenticatedIdempotentHeaders[P, Q, B, M, R any](e AuthenticatedIdempotentEndpoint[P, Q, B, M, R], fn func(context.Context, R) ([]ResponseHeader, error)) AuthenticatedIdempotentEndpoint[P, Q, B, M, R]
AuthenticatedIdempotentHeaders returns an endpoint with application headers captured for exact replay.
func IdempotentAuthenticated ¶
func IdempotentAuthenticated[P, Q, B, M, R any](endpoint AuthenticatedEndpoint[P, Q, B, M, R], store *idempotency.Store, definition idempotency.Definition) AuthenticatedIdempotentEndpoint[P, Q, B, M, R]
IdempotentAuthenticated binds an authenticated endpoint to a versioned idempotency operation while preserving current authorization.
func (AuthenticatedIdempotentEndpoint[P, Q, B, M, R]) Handle ¶
func (e AuthenticatedIdempotentEndpoint[P, Q, B, M, R]) Handle(scope func(context.Context, M, Input[P, Q, B]) (idempotency.Scope, error), handler func(context.Context, *database.Tx, M, Input[P, Q, B]) (R, error)) RouteRegistration
Handle registers actor-aware scope and transaction callbacks; current authentication and authorization precede idempotent execution or replay.
type AuthenticatedRoute ¶
type AuthenticatedRoute[P, M any] struct { // contains filtered or unexported fields }
AuthenticatedRoute supplies a concrete verified model while retaining native transport capabilities. Raw request/response payloads remain explicit boundaries. Configure path, middleware and route scope before adding authentication.
func ConfigureAuthenticatedRoute ¶ added in v0.2.0
func ConfigureAuthenticatedRoute[P, M any](route AuthenticatedRoute[P, M], options ...GuardOption[M]) AuthenticatedRoute[P, M]
ConfigureAuthenticatedRoute applies guard options to a copy of route, retaining missing-option errors for validation.
func RequireRouteAuthentication ¶
func RequireRouteAuthentication[P, M any](route Route[P], authentication *Authentication, guard auth.Guard[M], options ...GuardOption[M]) AuthenticatedRoute[P, M]
RequireRouteAuthentication binds a raw route to required typed authentication and guard options.
type Authentication ¶
type Authentication struct {
// contains filtered or unexported fields
}
Authentication composes one registry and immutable HTTP input declarations. Each accepted request gets a fresh scope; callbacks finish before its cleanup. Construction performs no I/O and does not start a session/token service. Cookie sources are secure by default: see CookieCredential.
func NewAuthentication ¶
func NewAuthentication(registry *auth.Registry, sources ...CredentialSource) (*Authentication, error)
NewAuthentication binds credential sources to a registry, rejecting cookie sources without origin protection unless explicitly opted out.
func NewCookieAuthentication ¶
func NewCookieAuthentication(registry *auth.Registry, config CSRFConfig, sources ...CredentialSource) (*Authentication, error)
NewCookieAuthentication protects every selected cookie guard with the same origin policy, even under an API path. Use NewAuthentication with only bearer sources for a stateless API; browser-session adapters already own CSRF.
func (*Authentication) CaptureCredentials ¶
func (a *Authentication) CaptureCredentials(r *stdhttp.Request) (auth.Credentials, error)
CaptureCredentials snapshots the declared HTTP inputs without retaining the request or a resolved subject. A long-lived transport must create and close a fresh Registry().NewScope for every authorization boundary. Browser session capture reuses secure-cookie validation; it neither creates nor rotates a session. Upgraded transports must independently enforce their handshake origin policy: safe-method CSRF rules are not WebSocket authorization.
func (*Authentication) Registry ¶
func (a *Authentication) Registry() *auth.Registry
Registry returns the immutable declaration/capacity owner for another typed transport adapter. It does not authenticate a request or expose credentials.
type AuthenticationInfo ¶
type AuthenticationInfo struct {
Guard auth.GuardName `json:"guard"`
Provider auth.ProviderName `json:"provider"`
Optional bool `json:"optional"`
Credential CredentialInfo `json:"credential"`
RequiredScopes []auth.AccessScopeName `json:"required_scopes,omitempty"`
RequiredPermissions []auth.PermissionName `json:"required_permissions,omitempty"`
}
AuthenticationInfo is inspection/client-contract metadata, never credential material. Guard/provider names come from the registered typed declaration.
type Binding ¶
Binding is a typed stage that runs after request authorization and before validation. It resolves request state, such as a route model, and returns the handler that completes the request, closing over that state so the handler never repeats the work. Model binding (http/modelbinding) uses it, so a missing bound resource is a 404, or a resource policy denial a 403, before body validation can report 422. A returned error is published as returned.
type BindingTransport ¶ added in v0.2.0
type BindingTransport[P, Q, B, R any] struct { // contains filtered or unexported fields }
BindingTransport exposes the explicit pre-validation binding stage.
func AfterValidation ¶ added in v0.2.0
func AfterValidation[P, Q, B, R any](transport HandlerTransport[P, Q, B, R]) BindingTransport[P, Q, B, R]
AfterValidation adapts a handler transport to run binding after its validation stage.
func ForBinding ¶ added in v0.2.0
func ForBinding[P, Q, B, R any](endpoint Endpoint[P, Q, B, R]) BindingTransport[P, Q, B, R]
ForBinding exposes the endpoint's binding stage while preserving its request and response types.
func ForSignedBinding ¶ added in v0.2.0
func ForSignedBinding[P, Q, B, R any](endpoint SignedEndpoint[P, Q, B, R]) BindingTransport[P, Q, B, R]
ForSignedBinding exposes the signed endpoint's binding stage.
func (BindingTransport[P, Q, B, R]) Description ¶ added in v0.2.0
func (t BindingTransport[P, Q, B, R]) Description() (EndpointInfo, error)
Description validates the binding transport and returns its endpoint metadata.
func (BindingTransport[P, Q, B, R]) HandleBound ¶ added in v0.2.0
func (t BindingTransport[P, Q, B, R]) HandleBound(bind Binding[P, Q, B, R]) RouteRegistration
HandleBound registers the binding, retaining invalid transport or nil-binding errors in the registration.
func (BindingTransport[P, Q, B, R]) Validate ¶ added in v0.2.0
func (t BindingTransport[P, Q, B, R]) Validate() error
Validate checks the adapter callbacks and underlying transport; a zero transport is invalid.
type Body ¶
type Body[B any] struct { // contains filtered or unexported fields }
Body is a typed request payload contract. Its zero value is invalid.
func FormBody ¶
FormBody uses the existing typed URL bindings as an independent URL-encoded request body. Query parameters never satisfy these body fields. Reuse generated form/query descriptors and MergeQueries/EmbedQuery for explicit composition.
func MFARecoveryBody ¶
func MFARecoveryBody() Body[MFARecoveryRequest]
MFARecoveryBody returns the shared typed JSON recovery-code request descriptor.
func MFATOTPBody ¶
func MFATOTPBody() Body[MFATOTPRequest]
MFATOTPBody uses generated bounded JSON decoding: required fields, duplicate and unknown names, nulls and invalid credential/code syntax are rejected.
func MultipartBody ¶
MultipartBody declares a generated or handwritten typed multipart form.
func RawRequestBody ¶
RawRequestBody declares a raw request body accepting the given media types, for example application/octet-stream. The request Content-Type must match one of them (parameters such as charset are kept and not compared) with identity Content-Encoding; otherwise the request is rejected with 415 before hooks run. Metadata, OpenAPI and generated clients describe it as binary content.
func RefreshTokenBody ¶
func RefreshTokenBody() Body[RefreshTokenRequest]
RefreshTokenBody uses the same generated DTO metadata as contract export. Unknown, duplicate, missing, null and malformed credential fields are rejected by the ordinary bounded JSON decoder before a refresh handler runs.
func RefreshTokenCookie ¶
func RefreshTokenCookie(cookie RefreshCookie) Body[RefreshTokenRequest]
RefreshTokenCookie reads the refresh credential only from the refresh cookie. The request takes no body and, through EmptyQuery, no query parameters. A missing or malformed cookie is unauthenticated. Handlers stay as for RefreshTokenBody: pass Body.RefreshToken.Secret() to Tokens.Refresh. Any 401 response of the endpoint, including a revoked or replayed family, clears the cookie. Pair it with TokenCookieResponse so the rotated secret is set again.
func RefreshTokenCookieLogout ¶
func RefreshTokenCookieLogout(cookie RefreshCookie) Body[RefreshCookieLogoutRequest]
RefreshTokenCookieLogout is the browser logout body: the refresh cookie itself authenticates the logout, so an expired access token does not prevent it. Like RefreshTokenCookie it reads only the cookie and accepts no body; a missing, repeated or malformed cookie is absent rather than unauthenticated, so logout is idempotent. Pair it with ClearRefreshCookie; validation rejects any other response. The handler passes a present credential to Tokens.LogoutRefresh:
if refresh, ok := input.Body.RefreshToken.Get(); ok {
_, err := tokens.LogoutRefresh(ctx, refresh.Secret())
return foundryhttp.NoContent{}, err
}
return foundryhttp.NoContent{}, nil
Success clears the cookie; a transient failure keeps it so the client retries.
type BrowserSessionConfig ¶
type BrowserSessionConfig struct {
Cookie CookieName
Options CookieOptions
CSRF CSRFConfig
Clock clock.Clock
}
BrowserSessionConfig owns browser scope and CSRF trust. Persistence lifetimes come from session.Config; MaxAge/Expires are computed from issued metadata. Clock must agree with the persistence adapter's clock. No I/O occurs at assembly.
func DefaultBrowserSessionConfig ¶
func DefaultBrowserSessionConfig() BrowserSessionConfig
DefaultBrowserSessionConfig returns a host-only session cookie with default options and the system clock.
func (BrowserSessionConfig) Validate ¶
func (c BrowserSessionConfig) Validate() error
Validate requires a clock, an HttpOnly cookie with server-owned expiry, valid cookie options and CSRF configuration.
type BrowserSessions ¶
type BrowserSessions[M model.Identifiable, K any] struct { // contains filtered or unexported fields }
BrowserSessions connects a typed persistent guard to HTTP cookies. Its Authentication automatically establishes CSRF and cookie ownership. Public login routes use Middleware. Operations require an ordinary typed JSON/empty endpoint, one credential change per request, and an unsafe HTTP method.
func NewBrowserSessions ¶
func NewBrowserSessions[M model.Identifiable, K any](registry *auth.Registry, sessions *session.Sessions[M, K], config BrowserSessionConfig) (*BrowserSessions[M, K], error)
NewBrowserSessions binds registered sessions to cookie authentication and CSRF protection after validating configuration.
func (*BrowserSessions[M, K]) Authentication ¶
func (b *BrowserSessions[M, K]) Authentication() *Authentication
Authentication returns the browser authentication transport, or nil for a nil binding.
func (*BrowserSessions[M, K]) CompleteMFA ¶
func (b *BrowserSessions[M, K]) CompleteMFA(ctx context.Context, factor auth.SecondFactor[M, K], options session.IssueOptions) (session.Info[M, K], error)
CompleteMFA consumes the bound pending cookie and stages a fresh full session. Use Middleware on this public challenge endpoint: an ordinary guarded endpoint rejects pending credentials. The existing CSRF, one-operation and response ownership checks apply. No cookie is published if completion/response fails. Completion may already have committed if later response preparation fails; the caller must restart login instead of replaying the consumed challenge.
func (*BrowserSessions[M, K]) Guard ¶
func (b *BrowserSessions[M, K]) Guard() auth.Guard[M]
Guard returns the session guard, or an undefined guard for a nil binding.
func (*BrowserSessions[M, K]) Impersonate ¶
func (b *BrowserSessions[M, K]) Impersonate(ctx context.Context, impersonation *session.Impersonation[M, K, M, K], target model.Reference[M, K], duration time.Duration) (session.Info[M, K], error)
Impersonate starts impersonating target and stages the impersonation session as this browser's cookie. The actor's own session is kept server-side, not revoked, so StopImpersonating can return to it. Authorize the actor before calling. Use it on an authenticated, CSRF-protected unsafe route.
func (*BrowserSessions[M, K]) Login ¶
func (b *BrowserSessions[M, K]) Login(ctx context.Context, proof auth.Proof[M, K], options session.IssueOptions) (session.Info[M, K], error)
Login issues a fresh credential from a trusted verified proof, then revokes the supplied previous cookie before staging its replacement. Errors publish neither secret nor cookie. Issuance counts against the active-session limit; a lost/error response can leave an unexposed session until expiry or explicit revocation.
func (*BrowserSessions[M, K]) Logout ¶
func (b *BrowserSessions[M, K]) Logout(ctx context.Context) error
Logout revokes the current credential, when present, and stages a clearing cookie in the bound request.
func (*BrowserSessions[M, K]) Middleware ¶
func (b *BrowserSessions[M, K]) Middleware() Middleware
Middleware binds browser-session request state and cookie handling to downstream requests.
func (*BrowserSessions[M, K]) RefuseImpersonation ¶
func (b *BrowserSessions[M, K]) RefuseImpersonation() Middleware
RefuseImpersonation returns actor-stage middleware that rejects impersonation sessions with auth.ImpersonationForbidden (HTTP 403) before decoding. Install it with WithActorMiddleware on routes that change credentials, email, MFA factors or the account itself.
func (*BrowserSessions[M, K]) RequirePasswordConfirmation ¶
func (b *BrowserSessions[M, K]) RequirePasswordConfirmation(within time.Duration) Middleware
RequirePasswordConfirmation returns actor-stage middleware for sensitive routes authenticated by this browser guard. It rejects the request with auth.ConfirmationRequired (HTTP 403) unless the current session re-entered its password within the window, checked against the session store's clock. Install it with WithActorMiddleware. A confirmation route re-verifies the password (auth.PasswordLogin.Confirm) and then calls session.Sessions.ConfirmCurrent.
func (*BrowserSessions[M, K]) Rotate ¶
Rotate replaces the current session secret and stages its cookie, returning the new session metadata.
func (*BrowserSessions[M, K]) StopImpersonating ¶
func (b *BrowserSessions[M, K]) StopImpersonating(ctx context.Context, impersonation *session.Impersonation[M, K, M, K]) (session.Info[M, K], error)
StopImpersonating ends the impersonation behind the current cookie and stages the original actor's session again under a fresh secret, keeping its original expiry (Impersonation.Resume). When the actor's session ended meanwhile, the impersonation still ends, the cookie is cleared and auth.Unauthenticated is returned.
func (*BrowserSessions[M, K]) Validate ¶
func (b *BrowserSessions[M, K]) Validate() error
Validate checks that the browser adapter, authentication transport and sessions are configured.
type CORSConfig ¶
type CORSConfig struct {
Origins []Origin
// OriginPatterns adds exact non-HTTP(S) origins (capacitor://localhost,
// tauri://localhost, chrome-extension://<id>) and validated HTTP(S)
// subdomain wildcards (https://*.example.com). A matching request Origin is
// reflected exactly. Unlisted and malformed origins receive no sharing
// headers; ordinary requests still reach the handler.
OriginPatterns []OriginPattern
AnyOrigin bool
Methods []Method
AnyMethod bool
Headers []HeaderName
AnyHeaders bool
ExposeHeaders []HeaderName
Credentials bool
// MaxAge is a whole number of seconds from zero through 24 hours.
// Zero explicitly disables preflight caching.
MaxAge time.Duration
// Paths selects a complete replacement policy for request paths equal to
// or below a prefix; the longest matching prefix wins and other requests
// use this policy. Path policies cannot declare nested Paths.
Paths []CORSPath
}
CORSConfig declares browser response sharing. The zero value permits no origins or preflight methods. Lists and wildcard flags are mutually exclusive. AnyHeaders/AnyMethod answer with validated requested names/methods, including credentialed preflights. AnyOrigin cannot be combined with Credentials.
func (CORSConfig) Validate ¶
func (c CORSConfig) Validate() error
Validate checks that the CORS declaration can be compiled.
type CORSPath ¶
type CORSPath struct {
Prefix string
Policy CORSConfig
}
CORSPath applies Policy to requests whose decoded URL path equals Prefix or continues below it at a segment boundary (/api matches /api and /api/x, not /apix). Prefix is an absolute, clean path without a trailing slash.
type CSPConfig ¶
CSPConfig permits independent enforced and report-only policies. Zero emits neither. Declarations are copied during middleware construction.
type CSPNonce ¶
type CSPNonce struct {
// contains filtered or unexported fields
}
CSPNonce is an opaque, request-scoped random value. String returns its base64 value for an HTML nonce attribute; it is not pre-escaped or trusted markup.
func CSPNonceFromContext ¶
CSPNonceFromContext returns the value shared by the request's enforced and report-only policies, if either declares CSPNonceSource. Never copy this value into a cached page or use it to bless untrusted script/style content.
type CSPPolicy ¶
type CSPPolicy struct {
DefaultSrc, ScriptSrc, ScriptSrcElem, ScriptSrcAttr []CSPSource
StyleSrc, StyleSrcElem, StyleSrcAttr []CSPSource
ChildSrc, ConnectSrc, FontSrc, FrameSrc, ImgSrc []CSPSource
ManifestSrc, MediaSrc, ObjectSrc, WorkerSrc []CSPSource
BaseURI, FormAction, FrameAncestors []CSPSource
Sandbox []CSPSandboxToken
UpgradeInsecureRequests bool
ReportTo CSPReportGroup
ReportURI []CSPReportURI
}
CSPPolicy describes one policy. Nil source slices omit a directive; an explicitly empty source slice emits 'none'. Sandbox has the same presence rule, with an empty slice enabling the full sandbox. A wholly empty policy is rejected. Browser enforcement and reporting remain browser responsibilities.
type CSPReportGroup ¶
type CSPReportGroup string
CSPReportGroup names a Reporting-Endpoints group configured separately.
type CSPReportURI ¶
type CSPReportURI string
CSPReportURI is a legacy report-uri destination: an absolute HTTP(S) URL or absolute local path. Reporting endpoint handlers must be registered separately.
type CSPSandboxToken ¶
type CSPSandboxToken string
CSPSandboxToken is one explicit permission granted back to a CSP sandbox.
const ( CSPSandboxDownloads CSPSandboxToken = "allow-downloads" CSPSandboxForms CSPSandboxToken = "allow-forms" CSPSandboxModals CSPSandboxToken = "allow-modals" CSPSandboxOrientationLock CSPSandboxToken = "allow-orientation-lock" CSPSandboxPointerLock CSPSandboxToken = "allow-pointer-lock" CSPSandboxPopups CSPSandboxToken = "allow-popups" CSPSandboxPopupsEscape CSPSandboxToken = "allow-popups-to-escape-sandbox" CSPSandboxPresentation CSPSandboxToken = "allow-presentation" CSPSandboxSameOrigin CSPSandboxToken = "allow-same-origin" CSPSandboxScripts CSPSandboxToken = "allow-scripts" CSPSandboxStorageAccess CSPSandboxToken = "allow-storage-access-by-user-activation" )
func (CSPSandboxToken) Validate ¶
func (t CSPSandboxToken) Validate() error
Validate accepts only supported content security policy sandbox tokens.
type CSPSource ¶
type CSPSource struct {
// contains filtered or unexported fields
}
CSPSource is one source expression. Use a constructor; its zero value is invalid. Dynamic host and scheme inputs are validated during assembly.
func CSPHostSource ¶
CSPHostSource accepts a CSP host pattern, for example "https://*.example.test:443/assets/". It is not an arbitrary source-list string. Use ASCII/punycode hosts. CSP host grammar does not permit IPv6 literals.
func CSPNonceSource ¶
func CSPNonceSource() CSPSource
CSPNonceSource asks the middleware to generate one fresh nonce per request. Read the matching value with CSPNonceFromContext when rendering trusted tags. Static configured nonces are deliberately not accepted by this API.
func CSPReportSample ¶
func CSPReportSample() CSPSource
CSPReportSample returns the 'report-sample' source expression.
func CSPSchemeSource ¶
CSPSchemeSource takes a scheme without its colon, for example "https" or "data".
func CSPStrictDynamic ¶
func CSPStrictDynamic() CSPSource
CSPStrictDynamic returns the 'strict-dynamic' source expression.
func CSPUnsafeEval ¶
func CSPUnsafeEval() CSPSource
CSPUnsafeEval returns the 'unsafe-eval' source expression.
func CSPUnsafeHashes ¶
func CSPUnsafeHashes() CSPSource
CSPUnsafeHashes returns the 'unsafe-hashes' source expression.
func CSPUnsafeInline ¶
func CSPUnsafeInline() CSPSource
CSPUnsafeInline returns the 'unsafe-inline' source expression.
func CSPWasmUnsafeEval ¶
func CSPWasmUnsafeEval() CSPSource
CSPWasmUnsafeEval returns the 'wasm-unsafe-eval' source expression.
type CSRFConfig ¶
type CSRFConfig struct {
TrustedOrigins []Origin `config:",json"`
}
CSRFConfig lists exact additional origins trusted to submit browser requests. Zero configuration trusts only same-origin requests. Unsafe requests without Fetch Metadata or Origin evidence fail closed. Configure bearer API routes separately; CORS permission does not automatically grant CSRF trust.
func (CSRFConfig) Validate ¶
func (c CSRFConfig) Validate() error
Validate checks that the CSRF configuration can be compiled.
type CachePolicy ¶
type CachePolicy struct {
Visibility CacheVisibility
MaxAge time.Duration
StaleWhileRevalidate time.Duration
StaleIfError time.Duration
NoCache bool
MustRevalidate bool
Immutable bool
NoStore bool
ExpiresFrom clock.Clock
}
CachePolicy is a typed Cache-Control declaration for GET/HEAD responses. All durations are whole seconds from zero through one year; zero MaxAge sends max-age=0. SharedMaxAge (s-maxage) requires CachePublic. NoStore forbids storage and excludes every other directive. NoCache stores but revalidates each use, which composes with ETags for cheap 304 revalidation. ExpiresFrom, when set, also sends an Expires date of now+MaxAge for HTTP/1.0 caches using that application clock; HTTP/1.1 caches prefer max-age.
func NoStoreCachePolicy ¶
func NoStoreCachePolicy() CachePolicy
NoStoreCachePolicy forbids any cache from storing the response.
func (CachePolicy) Validate ¶
func (p CachePolicy) Validate() error
Validate checks that the cache policy can be compiled into response headers.
type CacheVisibility ¶
type CacheVisibility uint8
CacheVisibility selects which caches may store a response.
const ( // CachePrivate permits only the requesting user's browser cache. CachePrivate CacheVisibility = iota + 1 // CachePublic also permits shared caches such as CDNs and proxies. CachePublic )
type CompressionConfig ¶
type CompressionConfig struct {
Encoders []CompressionEncoder
MinBytes int
MaxConcurrent int
}
CompressionConfig chooses server preference order, bounded buffering and the maximum concurrently active encoders for each assembled middleware instance. The first equal-weight encoding wins. Saturation falls back to identity when accepted; when a client refuses identity the request waits briefly for an encoder, then returns 503 with Retry-After. Requests never queue unbounded encoder work. Encoder state is pooled per configured encoder and reused.
func DefaultCompressionConfig ¶
func DefaultCompressionConfig() CompressionConfig
DefaultCompressionConfig returns Brotli and gzip encoders with a 1024-byte threshold and 32 concurrent compression slots.
func (CompressionConfig) Validate ¶
func (c CompressionConfig) Validate() error
Validate checks encoder count, uniqueness, settings, threshold and concurrency bounds.
type CompressionEncoder ¶
type CompressionEncoder struct {
// contains filtered or unexported fields
}
CompressionEncoder is an immutable, validated adapter descriptor. Construct it through GzipCompression or BrotliCompression; its zero value is invalid.
func BrotliCompression ¶
func BrotliCompression(quality BrotliQuality, window BrotliWindow) CompressionEncoder
BrotliCompression declares a Brotli encoder with the supplied quality and window; Validate checks their bounds.
func GzipCompression ¶
func GzipCompression(level GzipLevel) CompressionEncoder
GzipCompression declares a gzip encoder with the supplied level; Validate checks its bounds.
func (CompressionEncoder) Encoding ¶
func (e CompressionEncoder) Encoding() ContentEncoding
Encoding returns the encoder's content-encoding name.
func (CompressionEncoder) Validate ¶
func (e CompressionEncoder) Validate() error
Validate checks the encoding and its supported level and window settings.
type ContentEncoding ¶
type ContentEncoding string
ContentEncoding is a response coding, distinct from header names and media types.
const ( GzipEncoding ContentEncoding = "gzip" BrotliEncoding ContentEncoding = "br" )
type Cookie ¶
type Cookie[V any] struct { // contains filtered or unexported fields }
Cookie is an immutable typed declaration. Models, enums and named scalar values retain their types through Read and Set. It is not a session or guard.
func DefineCookie ¶
func DefineCookie[V any](name CookieName, codec CookieCodec[V], options CookieOptions) Cookie[V]
DefineCookie captures scope and codec. Validate during assembly; operations also reject an invalid declaration. Custom codecs must be bounded and safe for concurrent use. Foundry waits for their completion and catches panic/Goexit.
func (Cookie[V]) Clear ¶
func (c Cookie[V]) Clear(w stdhttp.ResponseWriter) error
Clear expires exactly this declaration's name/domain/path, retaining security flags. Deleting one path cannot remove cookies deliberately set at other paths.
func (Cookie[V]) Encrypted ¶
func (c Cookie[V]) Encrypted(encrypter CookieEncrypter) EncryptedCookie[V]
Encrypted binds this cookie declaration to an encrypter.
func (Cookie[V]) Options ¶
func (c Cookie[V]) Options() CookieOptions
Options returns the cookie's declared attributes.
func (Cookie[V]) Read ¶
Read distinguishes absent from present-empty. Unrelated malformed cookies are ignored; only this name's own malformed value is a BadRequest. Repeated occurrences of this name, including identical values, read as absent because browser path ordering is not identity. Prefer __Host- names for credentials.
func (Cookie[V]) Set ¶
Set validates and formats before appending one Set-Cookie field. Invoke before response headers are committed. It never replaces other cookies or wraps w.
func (Cookie[V]) Signed ¶
func (c Cookie[V]) Signed(signer CookieSigner) SignedCookie[V]
Signed binds this cookie declaration to a signer.
type CookieCodec ¶
CookieCodec reuses the scalar conversion contract used by paths and queries. Cookie serialization has its own quoting, bounds and duplicate-name rules.
func Base64Cookie ¶
func Base64Cookie[V any](codec CookieCodec[V]) CookieCodec[V]
Base64Cookie explicitly encodes arbitrary text into canonical URL-safe cookie octets. It does not sign or encrypt the value. Signed cookies already encode their payload, so they do not require this adapter.
func BoolCookie ¶
func BoolCookie[V ~bool]() CookieCodec[V]
BoolCookie returns the typed boolean path codec for cookie values.
func FloatCookie ¶
func FloatCookie[V PathFloat]() CookieCodec[V]
FloatCookie preserves finite native/named floats; use TextCookie for exact decimals.
func IntegerCookie ¶
func IntegerCookie[V PathInteger]() CookieCodec[V]
IntegerCookie returns the typed integer path codec for cookie values.
func ModelIDCookie ¶
func ModelIDCookie[M any]() CookieCodec[model.ID[M]]
ModelIDCookie returns the model-owned identifier path codec for cookie values.
func SecretCookie ¶
func SecretCookie() CookieCodec[secret.String]
SecretCookie is an explicit credential transport codec: values stay redacted in Go and are revealed only when Cookie.Set emits the actual Set-Cookie value.
func StringCookie ¶
func StringCookie[V ~string]() CookieCodec[V]
StringCookie returns the typed string path codec for cookie values.
func TextCookie ¶
func TextCookie[V any, P PathTextPointer[V]]() CookieCodec[V]
TextCookie returns a cookie codec using V's text marshaling and pointer unmarshaling methods.
type CookieEncrypter ¶
type CookieEncrypter struct {
// contains filtered or unexported fields
}
CookieEncrypter supplies confidentiality, integrity, scope binding, expiry and key rotation through the application's encryption keyring (AES-256-GCM). New values use the keyring's active key; retained keys decrypt existing values, so rotation keeps sessions readable until an old key is removed. It does not revoke values or prevent replay before expiry.
func NewCookieEncrypter ¶
func NewCookieEncrypter(keyring *encryption.Keyring, applicationClock clock.Clock) (CookieEncrypter, error)
NewCookieEncrypter validates and binds the keyring and application clock.
func (CookieEncrypter) GoString ¶
func (e CookieEncrypter) GoString() string
GoString returns the redaction marker without exposing encryption keys.
func (CookieEncrypter) String ¶
func (e CookieEncrypter) String() string
String returns the redaction marker without exposing encryption keys.
func (CookieEncrypter) Validate ¶
func (e CookieEncrypter) Validate() error
Validate checks the keyring and requires a non-nil application clock.
type CookieName ¶
type CookieName string
CookieName is case-sensitive and distinct from HTTP header names.
func (CookieName) Validate ¶
func (n CookieName) Validate() error
Validate checks the cookie name using the HTTP token name rules.
type CookieOptions ¶
type CookieOptions struct {
Path string
Domain string
Secure bool
HTTPOnly bool
SameSite stdhttp.SameSite
Partitioned bool
MaxAge time.Duration
Expires time.Time
}
CookieOptions owns scope and browser persistence. Zero MaxAge/Expires means a session cookie; Clear performs deletion explicitly. MaxAge takes precedence over Expires, matching browser semantics. Durations must be whole seconds. Native SameSite values are reused, not represented by framework strings.
func DefaultCookieOptions ¶
func DefaultCookieOptions() CookieOptions
DefaultCookieOptions returns host-only, Secure, HttpOnly, SameSite=Lax scope at /. Local plain-HTTP applications may explicitly set Secure=false. Do not infer it from an unvalidated forwarding header; request-dependent policy uses IsSecure.
type CookieSigner ¶
type CookieSigner struct {
// contains filtered or unexported fields
}
CookieSigner supplies integrity, scope binding, expiry and rotation. It does not encrypt values, revoke sessions or prevent replay before expiry. Authentication remains a separate guard/provider concern. Application time is injected.
func NewCookieSigner ¶
func NewCookieSigner(keys SigningKeys, applicationClock clock.Clock) (CookieSigner, error)
NewCookieSigner validates and binds signing keys and a non-nil application clock.
func (CookieSigner) GoString ¶
func (s CookieSigner) GoString() string
GoString returns the redaction marker without exposing signing keys.
func (CookieSigner) String ¶
func (s CookieSigner) String() string
String returns the redaction marker without exposing signing keys.
func (CookieSigner) Validate ¶
func (s CookieSigner) Validate() error
Validate checks signing keys and requires a non-nil application clock.
type CredentialInfo ¶
type CredentialInfo struct {
Source auth.CredentialName `json:"source"`
Kind CredentialKind `json:"kind"`
Name string `json:"name"`
OriginProtection bool `json:"origin_protection,omitempty"`
}
CredentialInfo describes where the selected guard reads a credential. It contains only public transport names, never tokens or cookie values. Browser session cookies also expose their required native origin/CSRF protection.
func (CredentialInfo) Validate ¶
func (info CredentialInfo) Validate() error
Validate checks the credential source and supported credential transport metadata.
type CredentialKind ¶
type CredentialKind string
CredentialKind identifies how an HTTP request supplies an authentication credential.
const ( BearerCredentialKind CredentialKind = "bearer" CookieCredentialKind CredentialKind = "cookie" // TicketCredentialKind identifies a server-issued, single-use query credential. TicketCredentialKind CredentialKind = "ticket" )
type CredentialSource ¶
type CredentialSource struct {
// contains filtered or unexported fields
}
CredentialSource snapshots one transport input into a named secret. Sources never inspect URLs, request bodies, models, or serialized attribution.
func BearerCredential ¶
func BearerCredential(name auth.CredentialName) CredentialSource
BearerCredential accepts exactly one Authorization field with the Bearer scheme and a bounded RFC 6750 token. Repeated/malformed values are rejected; a missing field is absent. A query-string token is never a fallback.
func CookieCredential ¶
func CookieCredential(name auth.CredentialName, cookie Cookie[secret.String]) CredentialSource
CookieCredential reuses a typed secret cookie's bounded parser, duplicate detection and configuration. Cookie values still require strategy verification; parsing is not authentication. Browsers attach cookies to cross-site requests, so NewAuthentication rejects a cookie source unless NewCookieAuthentication (or a browser-session adapter) supplies origin/CSRF protection or the source explicitly opts out with WithoutOriginProtection.
func (CredentialSource) WithoutOriginProtection ¶
func (s CredentialSource) WithoutOriginProtection() CredentialSource
WithoutOriginProtection explicitly opts a cookie source out of the origin/CSRF requirement enforced by NewAuthentication. Use it only when another layer owns cross-site protection (for example a WebSocket upgrade that validates Origin, or routes that never change state). Bearer sources are unaffected.
type CrossOriginEmbedderPolicy ¶
type CrossOriginEmbedderPolicy string
CrossOriginEmbedderPolicy selects Cross-Origin-Embedder-Policy. Zero omits it. require-corp or credentialless, with an opener policy of same-origin, enables cross-origin isolation; every embedded resource must then opt in.
const ( EmbedderRequireCORP CrossOriginEmbedderPolicy = "require-corp" EmbedderCredentialless CrossOriginEmbedderPolicy = "credentialless" EmbedderUnsafeNone CrossOriginEmbedderPolicy = "unsafe-none" )
func (CrossOriginEmbedderPolicy) Validate ¶
func (p CrossOriginEmbedderPolicy) Validate() error
Validate accepts an omitted or supported cross-origin embedder policy.
type CrossOriginOpenerPolicy ¶
type CrossOriginOpenerPolicy string
CrossOriginOpenerPolicy selects Cross-Origin-Opener-Policy. Zero omits it. same-origin isolates the browsing context group from cross-origin popups and openers; OAuth or payment popups may need same-origin-allow-popups.
const ( OpenerSameOrigin CrossOriginOpenerPolicy = "same-origin" OpenerSameOriginAllowPopups CrossOriginOpenerPolicy = "same-origin-allow-popups" OpenerNoOpenerAllowPopups CrossOriginOpenerPolicy = "noopener-allow-popups" OpenerUnsafeNone CrossOriginOpenerPolicy = "unsafe-none" )
func (CrossOriginOpenerPolicy) Validate ¶
func (p CrossOriginOpenerPolicy) Validate() error
Validate accepts an omitted or supported cross-origin opener policy.
type CrossOriginResourcePolicy ¶
type CrossOriginResourcePolicy string
CrossOriginResourcePolicy selects Cross-Origin-Resource-Policy, which limits which sites may load this response as a no-cors subresource. Zero omits it.
const ( ResourceSameOrigin CrossOriginResourcePolicy = "same-origin" ResourceSameSite CrossOriginResourcePolicy = "same-site" ResourceCrossOrigin CrossOriginResourcePolicy = "cross-origin" )
func (CrossOriginResourcePolicy) Validate ¶
func (p CrossOriginResourcePolicy) Validate() error
Validate accepts an omitted or supported cross-origin resource policy.
type Disposition ¶
type Disposition string
Disposition selects how a browser should handle a file representation. Filename metadata is advisory; it never selects a server filesystem path.
const ( DispositionAttachment Disposition = "attachment" DispositionInline Disposition = "inline" )
func (Disposition) HeaderValue ¶
func (d Disposition) HeaderValue(name string) (HeaderValue, error)
HeaderValue supplies a bounded Content-Disposition value with an ASCII fallback followed by an RFC6266/RFC5987 UTF-8 filename. It shares display-name normalization with uploads and prevents paths or control bytes entering the header. The zero disposition is invalid; choose attachment or inline.
func (Disposition) Validate ¶
func (d Disposition) Validate() error
Validate accepts only attachment or inline disposition.
type Download ¶
type Download struct {
// contains filtered or unexported fields
}
Download is a deferred seekable file representation, not a JSON response DTO. Copies retain the source callback but open separate request-owned content.
func DownloadFrom ¶
func DownloadFrom(source DownloadSource) Download
DownloadFrom binds a download source with default file presentation.
func LocalDownload ¶
LocalDownload opens a regular file relative to an application-owned os.Root. The caller owns the root's lifecycle; Foundry owns each opened file. Paths use fs.ValidPath's relative slash-separated form and never come from display names. The root confines symlink resolution; a valid-looking path alone does not.
func (Download) MarshalJSON ¶
MarshalJSON prevents accidental serialization of a deferred file response.
func (Download) WithDisposition ¶
func (d Download) WithDisposition(disposition Disposition) Download
WithDisposition returns a download with the selected disposition.
func (Download) WithEntityTag ¶
WithEntityTag returns a download with an explicitly supplied entity tag.
func (Download) WithMediaType ¶
WithMediaType returns a download with an explicitly supplied media type.
type DownloadContent ¶
type DownloadContent struct {
Body io.ReadSeekCloser
Name string
MediaType MediaType
Modified time.Time
EntityTag EntityTag
}
DownloadContent describes one opened seekable representation. Ownership of Body transfers to Foundry when the source returns, including alongside an error. Before returning, the source owns cleanup of any resources it opens. Source reads must honor the context supplied to DownloadSource.
type DownloadSource ¶
type DownloadSource func(context.Context) (DownloadContent, error)
DownloadSource opens content after a successful endpoint handler. It is not evaluated during route construction or when input/authorization fails.
type ETagConfig ¶
type ETagConfig struct {
MaxBytes int64
MaxConcurrent int
// AdmissionWait bounds the wait for a large-capture slot, from zero (no
// wait) through five seconds. The request context also ends the wait.
AdmissionWait time.Duration
}
ETagConfig bounds automatic response hashing. Captures larger than MaxBytes pass through in order without an automatic validator. Captures up to one 32 KiB page, and complete bodies written once with their declared length, need no shared slot. At most MaxConcurrent larger captures are buffered per assembled middleware; another waits up to AdmissionWait for a slot and then passes through without a validator. Worst-case large-capture memory is MaxConcurrent*MaxBytes. Buffering reserves memory only as bytes arrive.
func DefaultETagConfig ¶
func DefaultETagConfig() ETagConfig
DefaultETagConfig returns default automatic ETag capture, concurrency and admission-wait bounds.
func (ETagConfig) Validate ¶
func (c ETagConfig) Validate() error
Validate checks automatic ETag capture size, concurrency and admission-wait bounds.
type EncryptedCookie ¶
type EncryptedCookie[V any] struct { // contains filtered or unexported fields }
EncryptedCookie preserves the cookie's concrete value type while keeping the value confidential. The encoded value is sealed with the application's encryption keyring, bound to this cookie's name, domain, path and security flags, and carries its MaxAge/Expires deadline inside the ciphertext. The decoder runs only after authentication succeeds. The envelope, including a 28-byte nonce/tag and base64url encoding, must fit MaxCookieBytes.
func (EncryptedCookie[V]) Clear ¶
func (c EncryptedCookie[V]) Clear(w stdhttp.ResponseWriter) error
Clear validates the encrypted cookie and adds its clearing Set-Cookie header.
func (EncryptedCookie[V]) GoString ¶
func (c EncryptedCookie[V]) GoString() string
GoString returns the encrypted cookie's name label without exposing values.
func (EncryptedCookie[V]) Name ¶
func (c EncryptedCookie[V]) Name() CookieName
Name returns the underlying cookie name.
func (EncryptedCookie[V]) Options ¶
func (c EncryptedCookie[V]) Options() CookieOptions
Options returns the underlying cookie attributes.
func (EncryptedCookie[V]) Read ¶
Read distinguishes absent from present values. Malformed, tampered, expired, rescoped and retired-key values return BadRequest wrapping ErrInvalidEncryptedCookie.
func (EncryptedCookie[V]) Set ¶
func (c EncryptedCookie[V]) Set(ctx context.Context, w stdhttp.ResponseWriter, v V) error
Set formats and encrypts v and adds its Set-Cookie header after checking cancellation.
func (EncryptedCookie[V]) String ¶
func (c EncryptedCookie[V]) String() string
String returns a label containing the encrypted cookie's name.
func (EncryptedCookie[V]) Validate ¶
func (c EncryptedCookie[V]) Validate() error
Validate checks the cookie declaration and encrypter.
type Endpoint ¶
type Endpoint[P, Q, B, R any] struct { // contains filtered or unexported fields }
Endpoint composes the existing route, query and payload descriptors. Assembly performs no I/O. Handle validates the complete declaration before registration.
func AuthorizeEndpoint ¶ added in v0.2.0
func AuthorizeEndpoint[P, Q, B, R any](e Endpoint[P, Q, B, R], authorize RequestAuthorization[P, Q, B]) Endpoint[P, Q, B, R]
AuthorizeEndpoint replaces the optional request authorization callback. Use an authenticated endpoint's version when authorization needs a concrete actor.
func BodyExample ¶ added in v0.2.0
BodyExample documents an example JSON request body. It is encoded now through the endpoint's own body contract, so it cannot disagree with the declared schema; the endpoint retains only the encoded bytes.
func ConfigureEndpoint ¶ added in v0.2.0
func ConfigureEndpoint[P, Q, B, R any](endpoint Endpoint[P, Q, B, R], options ...EndpointOption) Endpoint[P, Q, B, R]
ConfigureEndpoint applies declaration options to a copy of endpoint and retains option errors for validation.
func DefineEndpoint ¶
func DefineEndpoint[P, Q, B, R any](route Route[P], query Query[Q], body Body[B], response Response[R], options ...EndpointOption) Endpoint[P, Q, B, R]
DefineEndpoint connects typed path, query, body and response contracts with default limits and the supplied options.
func EndpointHeaders ¶ added in v0.2.0
func EndpointHeaders[P, Q, B, R any](e Endpoint[P, Q, B, R], prepare ResponseHeaders[R]) Endpoint[P, Q, B, R]
EndpointHeaders derives response headers from the handler's successful result, for example Location for a created resource (see RouteLocation) or Cache-Control for a read. prepare runs after the handler succeeded and before the response is encoded; a returned error or an invalid header is an internal failure and no success is published. It replaces a prior callback.
Allowed names are Location, Content-Location, Content-Language, Cache-Control, Expires, Last-Modified, Link and Vary, plus application X-* headers other than proxy, framework and security headers (such as X-Accel-*, X-Sendfile, X-Forwarded-*, X-Request-Id and X-Frame-Options). Values are validated as HeaderValue. Link and Vary may repeat and Vary adds to framework values; other names appear at most once. At most 16 headers apply per response. JSON and empty responses support it; credential responses and file or stream responses do not. Idempotent endpoints declare replayable headers with IdempotentHeaders instead.
func PrepareEndpoint ¶ added in v0.2.0
func PrepareEndpoint[P, Q, B, R any](e Endpoint[P, Q, B, R], prepare Preparation[P, Q, B]) Endpoint[P, Q, B, R]
PrepareEndpoint replaces the optional preparation callback on an independent endpoint. An explicitly nil callback is invalid at registration. Prohibited and Absent rules also check original input before this callback can transform it.
func ResponseExample ¶ added in v0.2.0
ResponseExample documents an example JSON response, encoded through the endpoint's own response contract like WithBodyExample.
func ValidateBody ¶ added in v0.2.0
func ValidateBody[P, Q, B, R any](e Endpoint[P, Q, B, R], rules ...validation.Rule[B]) Endpoint[P, Q, B, R]
ValidateBody adds rules for the decoded body. Use generated field declarations and Optional/Nullable rules to retain wire names and presence.
func ValidateInput ¶ added in v0.2.0
func ValidateInput[P, Q, B, R any](e Endpoint[P, Q, B, R], rules ...validation.Rule[Input[P, Q, B]]) Endpoint[P, Q, B, R]
ValidateInput adds request rules in declaration order, including comparisons across parameter sources. It returns an independent endpoint. Rules execute after decoding, preparation and request authorization, before the handler; they must not mutate input values.
func ValidatePath ¶ added in v0.2.0
func ValidatePath[P, Q, B, R any](e Endpoint[P, Q, B, R], rules ...validation.Rule[P]) Endpoint[P, Q, B, R]
ValidatePath adds rules for the concrete path value. Diagnostics and metadata retain the path source prefix, including declared nested fields.
func ValidateQuery ¶ added in v0.2.0
func ValidateQuery[P, Q, B, R any](e Endpoint[P, Q, B, R], rules ...validation.Rule[Q]) Endpoint[P, Q, B, R]
ValidateQuery adds rules for the concrete query value.
func (Endpoint[P, Q, B, R]) Handle ¶
func (e Endpoint[P, Q, B, R]) Handle(handler Handler[P, Q, B, R]) RouteRegistration
Handle binds a handler with exactly these path/query/body/response types. Parsing, codec execution and handler callbacks finish before a response is committed. Cancellation never abandons an active callback or its resources.
A handler's outcome is authoritative. A returned error, including a declared application error, is published as returned. A successful result is prepared and written even if the request deadline expired after the handler returned; only an actual write failure can then prevent delivery.
func (Endpoint[P, Q, B, R]) URL ¶
URL generates a relative path and query from their concrete declarations. Neither an incoming host nor an arbitrary query string participates. Only the route and query declarations it uses are validated here, so link generation stays cheap; Handle validates the complete endpoint.
type EndpointInfo ¶
type EndpointInfo struct {
// TableOperation is the explicitly declared table association.
TableOperation *contract.TableOperationBinding `json:"table_operation,omitempty"`
Path []PathParameterInfo `json:"path"`
Route RouteInfo `json:"route"`
Query []QueryParameterInfo `json:"query"`
Body *PayloadInfo `json:"body,omitempty"`
Response *PayloadInfo `json:"response,omitempty"`
Status int `json:"status"`
// Statuses lists every declared success status, primary first, when the
// response declares alternatives (JSONResponses).
Statuses []int `json:"statuses,omitempty"`
// Redirect marks a RedirectResponse: Status is 3xx with a Location and no body.
Redirect bool `json:"redirect,omitempty"`
Limits EndpointLimits `json:"limits"`
Preparation bool `json:"preparation,omitempty"`
Validation *validation.Description `json:"validation,omitempty"`
Idempotency *IdempotencyInfo `json:"idempotency,omitempty"`
Errors []ErrorDefinition `json:"errors,omitempty"`
// RefreshCookie describes a browser refresh-token cookie the endpoint
// reads, sets or clears; it never contains a credential value.
RefreshCookie *RefreshCookieInfo `json:"refresh_cookie,omitempty"`
}
EndpointInfo is an owned snapshot of typed endpoint declarations. Query cardinality and codec-owned scalar metadata share the runtime declarations. Undescribed custom codecs retain nil metadata instead of a fabricated schema.
func InspectAuthenticated ¶ added in v0.2.0
func InspectAuthenticated[P, Q, B, M, R any](e AuthenticatedEndpoint[P, Q, B, M, R]) (EndpointInfo, error)
InspectAuthenticated validates the endpoint and returns metadata including its authentication requirements.
func InspectAuthenticatedIdempotent ¶ added in v0.2.0
func InspectAuthenticatedIdempotent[P, Q, B, M, R any](e AuthenticatedIdempotentEndpoint[P, Q, B, M, R]) (EndpointInfo, error)
InspectAuthenticatedIdempotent validates the endpoint and returns its authentication and idempotency metadata.
func InspectEndpoint ¶ added in v0.2.0
func InspectEndpoint[P, Q, B, R any](e Endpoint[P, Q, B, R]) (EndpointInfo, error)
InspectEndpoint validates before returning owned metadata for inspection.
func InspectIdempotent ¶ added in v0.2.0
func InspectIdempotent[P, Q, B, R any](e IdempotentEndpoint[P, Q, B, R]) (EndpointInfo, error)
InspectIdempotent validates the endpoint and returns its idempotency and optional signed-URL metadata.
func InspectOptional ¶ added in v0.2.0
func InspectOptional[P, Q, B, M, R any](e OptionalAuthenticationEndpoint[P, Q, B, M, R]) (EndpointInfo, error)
InspectOptional validates the endpoint and returns metadata including optional authentication.
func InspectSigned ¶ added in v0.2.0
func InspectSigned[P, Q, B, R any](e SignedEndpoint[P, Q, B, R]) (EndpointInfo, error)
InspectSigned returns validated endpoint metadata including signed-link policy.
func InspectSignedAuthenticated ¶ added in v0.2.0
func InspectSignedAuthenticated[P, Q, B, S, R any](e SignedAuthenticatedEndpoint[P, Q, B, S, R]) (EndpointInfo, error)
InspectSignedAuthenticated returns validated authentication, endpoint and signed-link metadata.
func InspectTicketAuthenticated ¶ added in v0.4.0
func InspectTicketAuthenticated[P, Q, B, M, R any](e TicketEndpoint[P, Q, B, M, R]) (EndpointInfo, error)
InspectTicketAuthenticated returns owned endpoint metadata with ticket authentication and the guard's scope and permission requirements.
type EndpointLimits ¶
type EndpointLimits struct {
Multipart MultipartLimits
Files FileResponseLimits
Query QueryLimits
Form QueryLimits
Body contract.JSONLimits
Response contract.JSONLimits
Validation validation.Limits
// Raw bounds a RawRequestBody. Zero is allowed on other endpoints.
Raw RawBodyLimits
}
EndpointLimits bounds query parsing, URL-encoded forms, multipart and JSON independently. The HTTP kernel's MaxBodyBytes remains an additional global input ceiling.
func DefaultEndpointLimits ¶
func DefaultEndpointLimits() EndpointLimits
DefaultEndpointLimits returns independent defaults without allocating payload buffers. Request body bytes use the framework's default HTTP body size. A response that exceeds its limits is an internal error whose redacted diagnostic names EndpointLimits.Response and the exceeded bound.
func (EndpointLimits) Validate ¶
func (l EndpointLimits) Validate() error
Validate checks endpoint budgets; zero form and raw budgets are inactive here, with body-specific requirements enforced at registration.
type EndpointOption ¶ added in v0.2.0
type EndpointOption interface {
// contains filtered or unexported methods
}
EndpointOption configures a declaration without erasing its request or response types.
func Errors ¶ added in v0.2.0
func Errors(declarations ...ErrorDeclaration) EndpointOption
Errors snapshots application error declarations for addition to an endpoint.
func InvalidEndpointOption ¶ added in v0.3.0
func InvalidEndpointOption(cause error) EndpointOption
InvalidEndpointOption lets a typed adapter retain a construction failure in endpoint validation without replacing an earlier declaration error. The cause remains inspectable; its formatting methods are never invoked. A nil cause still produces an invalid declaration.
Example: http.ConfigureEndpoint(endpoint, http.InvalidEndpointOption(cause))
func Limits ¶ added in v0.2.0
func Limits(limits EndpointLimits) EndpointOption
Limits declares the endpoint's decoding, response and validation budgets.
func TableOperation ¶ added in v0.3.0
func TableOperation(binding contract.TableOperationBinding) EndpointOption
TableOperation declares an endpoint's table association. Manifest construction validates its registered table and payload contracts. Repeated declarations fail.
type EntityTag ¶
type EntityTag string
EntityTag is an HTTP representation validator. Zero omits the validator; nonzero values use the quoted strong or W/quoted weak wire representation. A tag is supplied by the representation owner, never guessed from its name.
type ErrorCode ¶
type ErrorCode string
ErrorCode is a transport classification with a fixed public message and HTTP status. Built-in codes implement error, so a handler may return NotFound or wrap it with an ordinary Go error. Custom codes require DefineError; returning an undeclared code alone exposes InternalError.
const ( BadRequest ErrorCode = "bad_request" Unauthenticated ErrorCode = "unauthenticated" Forbidden ErrorCode = "forbidden" MFARequired ErrorCode = "mfa_required" NotFound ErrorCode = "not_found" NotAcceptable ErrorCode = "not_acceptable" MethodNotAllowed ErrorCode = "method_not_allowed" Conflict ErrorCode = "conflict" PreconditionFailed ErrorCode = "precondition_failed" RangeNotSatisfiable ErrorCode = "range_not_satisfiable" ValidationFailed ErrorCode = "validation_failed" PayloadTooLarge ErrorCode = "payload_too_large" UnsupportedMediaType ErrorCode = "unsupported_media_type" RequestTimeout ErrorCode = "request_timeout" RateLimited ErrorCode = "rate_limited" InternalError ErrorCode = "internal_error" )
func (ErrorCode) Error ¶
Error returns a recognized built-in code, falling back to InternalError for unknown codes.
func (ErrorCode) FoundryDiagnostic ¶
FoundryDiagnostic contributes the public transport code to redacted diagnostics.
type ErrorDeclaration ¶
type ErrorDeclaration struct {
// contains filtered or unexported fields
}
ErrorDeclaration is an immutable application failure with explicit public metadata. Return it directly as an ordinary Go error, or use WithCause to retain private diagnostic context. An invalid or zero declaration is never published; Validate and endpoint assembly report its configuration error.
func DefineError ¶
func DefineError(code ErrorCode, status int, message string) ErrorDeclaration
DefineError declares a stable code, error status (400–599), and static public message. The same value supplies runtime responses and endpoint metadata. Built-in codes are reserved. MessageDefinition enables localized messages.
func (ErrorDeclaration) Description ¶
func (d ErrorDeclaration) Description() (ErrorDefinition, error)
Description validates and returns a value snapshot. Editing it does not change this declaration or any already registered endpoint.
func (ErrorDeclaration) Error ¶
func (d ErrorDeclaration) Error() string
Error returns the declaration's HTTP error code text.
func (ErrorDeclaration) MessageDefinition ¶
func (d ErrorDeclaration) MessageDefinition() (i18n.MessageDefinition, error)
MessageDefinition returns the parameter-free catalog signature (http.error.<code>) that localizes this error's public message in locale-enabled HTTP applications. Register it with the application's message declarations and supply translations; locales without one keep the declared message. Code, status and endpoint metadata are unchanged.
func (ErrorDeclaration) Validate ¶
func (d ErrorDeclaration) Validate() error
Validate requires a semantic nonreserved code, a 4xx or 5xx status and a bounded public message.
func (ErrorDeclaration) WithCause ¶
func (d ErrorDeclaration) WithCause(cause error) error
WithCause preserves errors.Is/errors.As and formats only the public code. Causes are never used as response messages or contract metadata.
type ErrorDefinition ¶
type ErrorDefinition struct {
Code ErrorCode `json:"error_code"`
Status int `json:"status"`
Message string `json:"message"`
}
ErrorDefinition is the shared runtime/client-contract description of a code. Returned definitions are value snapshots; editing one cannot change behavior.
func ErrorDefinitions ¶
func ErrorDefinitions() []ErrorDefinition
ErrorDefinitions returns the built-in catalog used by response encoding. Router.ErrorDefinitions adds declared application errors. Contract exporters must consume these catalogs instead of copying status maps.
type ErrorResponse ¶
type ErrorResponse struct {
Status int `json:"status"`
Code ErrorCode `json:"error_code"`
Message string `json:"message"`
RequestID attribution.RequestID `json:"request_id,omitempty"`
Issues []contract.Issue `json:"issues,omitempty"`
IssuesTruncated bool `json:"issues_truncated,omitempty"`
}
ErrorResponse is Foundry's public HTTP failure DTO. Models and internal causes are never serialized into this envelope.
type Event ¶
Event is one server-sent event. Data is encoded by the stream's declared JSON contract. ID and Name are optional single-line text (at most 1 KiB, no NUL); an empty Name is the client's default "message" event. A positive Retry advises the client's reconnection delay, sent in whole milliseconds.
type EventSink ¶
type EventSink[T any] struct { // contains filtered or unexported fields }
EventSink accepts events for one stream. Send is safe for concurrent use by the producer and goroutines it owns, until the producer returns.
func (*EventSink[T]) Send ¶
Send validates one event and queues it in order, waiting while the queue is full. It returns ctx's error if ctx ends first, fault.Closed once the stream has ended (client disconnect, deadline or write failure), and fault.Invalid for an invalid ID, Name or Retry. Events still queued when a stream ends early are discarded; after a producer returns normally they are all written.
type EventStreamConfig ¶
type EventStreamConfig struct {
// Queue bounds events accepted by Send but not yet written (1–4096). Send
// waits while the queue is full, so a slow client slows its producer.
Queue int
// Heartbeat writes a comment line when no event was written for this long,
// so idle proxies keep the connection open. Zero disables it; otherwise it
// must be at least one second.
Heartbeat time.Duration
// Data bounds each event's encoded payload.
Data contract.JSONLimits
}
EventStreamConfig bounds one text/event-stream response.
func DefaultEventStreamConfig ¶
func DefaultEventStreamConfig() EventStreamConfig
DefaultEventStreamConfig returns a 64-event queue, a 15-second heartbeat and 64 KiB event payloads.
func (EventStreamConfig) Validate ¶
func (c EventStreamConfig) Validate() error
Validate checks queue and data bounds and requires a disabled heartbeat or an interval of at least one second.
type Events ¶
type Events[T any] struct { // contains filtered or unexported fields }
Events is a typed endpoint's server-sent event stream. Build it with EventsFrom; its producer runs after the handler succeeded, while the response streams. Copies share the producer but run independently for each request.
func EventsFrom ¶
EventsFrom declares the stream's producer; see ServeEvents for its contract.
func (Events[T]) MarshalJSON ¶
MarshalJSON rejects implicit serialization; events require their response contract.
func (Events[T]) WithConfig ¶
func (e Events[T]) WithConfig(config EventStreamConfig) Events[T]
WithConfig replaces the queue and heartbeat. A typed endpoint bounds each event's data by its EndpointLimits.Response, which clients also receive, so config.Data is ignored here.
type FileResponseInfo ¶
type FileResponseInfo struct {
MediaTypes []MediaType `json:"media_types"`
Seekable bool `json:"seekable"`
}
FileResponseInfo describes declared media and native seek/range capability. File content has no implicit JSON schema. MediaTypes is an owned snapshot.
func (FileResponseInfo) TransferBytes ¶
func (info FileResponseInfo) TransferBytes(limits FileResponseLimits) (int64, error)
TransferBytes bounds a successful body, including multipart byte-range framing. Bytes alone bounds the representation; MIME framing can be larger than a small file. net/http falls back to the full representation when the sum of requested ranges exceeds its size. The standard MIME writer measures framing with its maximum supported boundary, so exporters do not recreate it.
type FileResponseLimits ¶
FileResponseLimits bounds a file representation and native range parsing. Unseekable streams use Bytes; only seekable downloads parse ranges. These limits are independent of buffered JSON response limits. Buffering does not grow with Bytes: the response streams through the native fixed copy buffer.
func DefaultFileResponseLimits ¶
func DefaultFileResponseLimits() FileResponseLimits
DefaultFileResponseLimits returns a one-gigabyte body limit with at most 16 ranges and 4096 range-header bytes.
func (FileResponseLimits) Validate ¶
func (l FileResponseLimits) Validate() error
Validate checks body and range bounds and rejects limits that could overflow range arithmetic.
type FramePolicy ¶
type FramePolicy string
FramePolicy selects the supported X-Frame-Options policy. Zero omits the header; use the default configuration to select FrameDeny explicitly.
const ( FrameDeny FramePolicy = "DENY" FrameSameOrigin FramePolicy = "SAMEORIGIN" )
func (FramePolicy) Validate ¶
func (p FramePolicy) Validate() error
Validate accepts an omitted, deny or same-origin frame policy.
type GuardBinding ¶
type GuardBinding[M any] struct { // contains filtered or unexported fields }
GuardBinding is a route group's concrete default actor. Separate model types require separate bindings; there is no runtime actor cast or global default.
func BindGuard ¶
func BindGuard[M any](authentication *Authentication, guard auth.Guard[M]) (GuardBinding[M], error)
BindGuard checks exact guard registration and credential-source availability in authentication.
func (GuardBinding[M]) Guard ¶
func (b GuardBinding[M]) Guard() auth.Guard[M]
Guard returns the bound authentication guard.
func (GuardBinding[M]) Select ¶
func (b GuardBinding[M]) Select(guard auth.Guard[M]) (GuardBinding[M], error)
Select returns another binding for this model, leaving the group's default unchanged. A different actor model cannot be passed to this method.
type GuardOption ¶ added in v0.2.0
type GuardOption[M any] interface { // contains filtered or unexported methods }
GuardOption preserves ownership of credential scopes and permissions.
func Permissions ¶ added in v0.2.0
func Permissions[M any](required ...auth.Permission[M]) GuardOption[M]
Permissions snapshots model permissions required by the authentication binding.
func Scopes ¶ added in v0.2.0
func Scopes[M any](required auth.AccessScopes[M]) GuardOption[M]
Scopes requires the credential to grant the supplied model-owned access scopes.
type GzipLevel ¶
type GzipLevel int
GzipLevel preserves gzip's supported levels, including its special defaults.
const ( GzipDefault GzipLevel = gzip.DefaultCompression GzipFastest GzipLevel = gzip.BestSpeed GzipSmallest GzipLevel = gzip.BestCompression )
type HSTSPolicy ¶
HSTSPolicy is an explicit Strict-Transport-Security declaration. MaxAge must be a nonnegative whole number of seconds; zero asks browsers to remove a remembered policy. IncludeSubDomains and Preload are explicit choices. Preload only emits the directive; it does not enroll a domain in any list.
func (HSTSPolicy) Validate ¶
func (p HSTSPolicy) Validate() error
Validate requires a nonnegative whole-second max age and enforces subdomain and one-year prerequisites for preload.
type Handler ¶
Handler receives decoded input and returns a declared response value. It owns domain operations and their transaction boundaries; it never receives a writer.
type HandlerTransport ¶ added in v0.2.0
type HandlerTransport[P, Q, B, R any] interface { // Validate checks the transport declaration. Validate() error // Description returns the endpoint's contract metadata. Description() (EndpointInfo, error) // Handle registers the typed handler with the transport. Handle(Handler[P, Q, B, R]) RouteRegistration }
HandlerTransport preserves typed handler registration, validation and metadata through endpoint adapters.
type HeaderName ¶
type HeaderName string
HeaderName is a declared HTTP field name, distinct from routes and values. Validate checks the ASCII field-name grammar before canonicalization.
const IdempotencyKeyHeader HeaderName = "Idempotency-Key"
func (HeaderName) Canonical ¶
func (n HeaderName) Canonical() (HeaderName, error)
Canonical returns Go's conventional casing after validating the field name.
func (HeaderName) Validate ¶
func (n HeaderName) Validate() error
Validate requires a nonempty HTTP token no longer than 256 bytes.
type HeaderValue ¶
type HeaderValue string
HeaderValue is an HTTP field value, distinct from a field name or method. Validation checks its byte bound and rejects control bytes except horizontal tab. A header-specific grammar, such as cookies or CSP, is a separate contract.
func (HeaderValue) Validate ¶
func (v HeaderValue) Validate() error
Validate checks the byte bound and rejects control bytes other than horizontal tabs.
type IPRateLimitOptions ¶
IPRateLimitOptions groups client addresses before the quota lookup. A single IPv6 subscriber usually controls at least a /64, so per-address IPv6 keys would let one client rotate through unlimited quotas. Prefix lengths are 1-32 for IPv4 and 1-128 for IPv6; zero values select the defaults.
func DefaultIPRateLimitOptions ¶
func DefaultIPRateLimitOptions() IPRateLimitOptions
DefaultIPRateLimitOptions keys IPv4 per address and IPv6 per /64 network.
func (IPRateLimitOptions) Validate ¶
func (o IPRateLimitOptions) Validate() error
Validate checks that the IP rate-limit options can be compiled.
type IdempotencyInfo ¶
type IdempotencyInfo struct {
Operation idempotency.OperationID `json:"operation"`
Version uint32 `json:"version"`
Header HeaderName `json:"header"`
MinKeyBytes int `json:"min_key_bytes"`
MaxKeyBytes int `json:"max_key_bytes"`
KeyPattern string `json:"key_pattern"`
Fingerprint string `json:"fingerprint"`
SuccessOnly bool `json:"success_only"`
DuplicateWaitMilliseconds int64 `json:"duplicate_wait_ms"`
RetentionSeconds int64 `json:"retention_seconds"`
ApplicationHeaders []HeaderName `json:"application_headers"`
}
IdempotencyInfo is the replay policy used by the handler and generated client. Retention is a minimum until explicit pruning, not automatic callback expiry.
func (IdempotencyInfo) Validate ¶
func (i IdempotencyInfo) Validate() error
Validate checks exported idempotency metadata against supported key, fingerprint, replay-header, wait and retention policies.
type IdempotentEndpoint ¶
type IdempotentEndpoint[P, Q, B, R any] struct { // contains filtered or unexported fields }
IdempotentEndpoint binds a typed endpoint to a versioned store operation and replayable response headers.
func Idempotent ¶
func Idempotent[P, Q, B, R any](endpoint Endpoint[P, Q, B, R], store *idempotency.Store, definition idempotency.Definition) IdempotentEndpoint[P, Q, B, R]
Idempotent supports transaction-bound JSON/empty operations on unsafe methods. Configure the ordinary endpoint's rules, hooks and response before adapting it.
func IdempotentHeaders ¶ added in v0.2.0
func IdempotentHeaders[P, Q, B, R any](e IdempotentEndpoint[P, Q, B, R], prepare func(context.Context, R) ([]ResponseHeader, error)) IdempotentEndpoint[P, Q, B, R]
IdempotentHeaders prepares bounded application headers inside the transaction. Only Location, Content-Language and ETag are replayable. Cookies, credentials, security, framing and request/trace headers never enter the stored outcome.
func IdempotentSigned ¶
func IdempotentSigned[P, Q, B, R any](endpoint SignedEndpoint[P, Q, B, R], store *idempotency.Store, definition idempotency.Definition) IdempotentEndpoint[P, Q, B, R]
IdempotentSigned binds signed endpoint execution to the versioned idempotency operation and preserves URL verification.
func (IdempotentEndpoint[P, Q, B, R]) Handle ¶
func (e IdempotentEndpoint[P, Q, B, R]) Handle(scope func(context.Context, Input[P, Q, B]) (idempotency.Scope, error), handler TransactionHandler[P, Q, B, R]) RouteRegistration
Handle derives trusted scope after the endpoint's validation and authorization. Scope callbacks must authenticate/verify public webhook requests on every call.
type Input ¶
type Input[P, Q, B any] struct { Path P Query Q Body B }
Input retains distinct, concrete parameter sources. A body field cannot replace a path or query field with the same name. Alias this instantiated type to give a domain handler a short request name.
type LocaleNegotiation ¶
type LocaleNegotiation struct {
QueryParameter string
Cookie CookieName
Preferred func(*stdhttp.Request) (i18n.LocaleID, bool, error)
}
LocaleNegotiation declares explicit request locale sources. In order, a query parameter, a cookie and an application preference (for example an authenticated user's stored locale) are consulted before a locale inherited on the request context, then Accept-Language, then the catalog default. Every value is matched against the catalog: malformed or unsupported values defer to the next source (a supported parent tag may match). The zero value consults only the context locale and Accept-Language.
Preferred is application code: it must honor the request context and be safe for concurrent use; its panics are contained and its errors are written as the shared error response. An authenticated preference needs the actor, so install LocaleWith on the authenticated route or scope, inside its authentication middleware, where it overrides a global Locale's selection.
func (LocaleNegotiation) Validate ¶
func (n LocaleNegotiation) Validate() error
Validate checks optional query-parameter and cookie names used for locale selection.
type MFAChallengeCredential ¶
type MFAChallengeCredential = authtransport.MFAChallengeCredential
MFAChallengeCredential retains redaction until its explicit Secret boundary.
type MFARecoveryRequest ¶
type MFARecoveryRequest = authtransport.MFARecoveryRequest
MFARecoveryRequest chooses a recovery code instead of a TOTP code.
type MFATOTPRequest ¶
type MFATOTPRequest = authtransport.MFATOTPRequest
MFATOTPRequest carries a pending token and a typed TOTP response. Completion verifies both; a syntactically valid Challenge grants no authority.
type MediaType ¶
type MediaType string
MediaType is a concrete response media type, optionally with parameters. Wildcards belong to negotiation and are not a representation's media type.
type Method ¶
type Method string
Method selects an origin-form HTTP method. CONNECT tunneling is outside the route contract. GET also matches HEAD, following net/http's routing semantics.
const ( GET Method = stdhttp.MethodGet HEAD Method = stdhttp.MethodHead POST Method = stdhttp.MethodPost PUT Method = stdhttp.MethodPut PATCH Method = stdhttp.MethodPatch DELETE Method = stdhttp.MethodDelete OPTIONS Method = stdhttp.MethodOptions TRACE Method = stdhttp.MethodTrace )
func AuthenticatedEndpointMethod ¶ added in v0.2.0
func AuthenticatedEndpointMethod[P, Q, B, M, R any](endpoint AuthenticatedEndpoint[P, Q, B, M, R]) Method
AuthenticatedEndpointMethod returns the endpoint's HTTP method.
func EndpointMethod ¶ added in v0.2.0
EndpointMethod returns the endpoint's declared HTTP method.
func OptionalEndpointMethod ¶ added in v0.2.0
func OptionalEndpointMethod[P, Q, B, M, R any](endpoint OptionalAuthenticationEndpoint[P, Q, B, M, R]) Method
OptionalEndpointMethod returns the endpoint's HTTP method.
func RouteMethod ¶ added in v0.2.0
RouteMethod returns the route's declared HTTP method.
func SignedAuthenticatedEndpointMethod ¶ added in v0.2.0
func SignedAuthenticatedEndpointMethod[P, Q, B, S, R any](e SignedAuthenticatedEndpoint[P, Q, B, S, R]) Method
SignedAuthenticatedEndpointMethod returns the endpoint's HTTP method.
func SignedEndpointMethod ¶ added in v0.2.0
func SignedEndpointMethod[P, Q, B, R any](e SignedEndpoint[P, Q, B, R]) Method
SignedEndpointMethod returns the endpoint's HTTP method.
func SignedRouteMethod ¶ added in v0.2.0
func SignedRouteMethod[P any](r SignedRoute[P]) Method
SignedRouteMethod returns the underlying HTTP method.
type Middleware ¶
type Middleware struct {
// contains filtered or unexported fields
}
Middleware is an immutable native HTTP wrapper declaration. Its factory runs once during assembly and must not start I/O or goroutines. Request handling remains synchronous; wrappers must not retain a writer after ServeHTTP ends.
func CORS ¶
func CORS(config CORSConfig) Middleware
CORS snapshots a browser response-sharing policy. Invalid configuration is returned by middleware assembly; CORSConfig.Validate can check it earlier. Apply it around the router so preflights do not require OPTIONS routes. Ordinary requests from disallowed, unknown or malformed origins still reach the handler without sharing headers; a preflight from them is 403. An OPTIONS request without Origin is not a preflight and reaches the handler. Path policies select a complete policy per prefix. Authentication, authorization and CSRF remain separate.
func CSRF ¶
func CSRF(config CSRFConfig) Middleware
CSRF uses Go's native cross-origin checks, bounded header parsing, and a scheme-aware Origin fallback. It preserves the native response writer. Run TrustedProxy first when the public scheme/host is supplied by a trusted edge.
func CacheControl ¶
func CacheControl(policy CachePolicy) Middleware
CacheControl applies a snapshotted policy to GET and HEAD responses before the next handler runs. It never replaces a Cache-Control value an outer middleware already chose (for example a browser session's no-store), handlers may still override it, and shared error responses replace it with no-store. A public policy is downgraded to private for requests carrying an Authorization header, so shared caches never store credentialed responses. Other methods are unchanged. Compose with ETags for conditional revalidation.
func Compression ¶
func Compression(config CompressionConfig) Middleware
Compression negotiates gzip/Brotli and streams through bounded prefix buffers. It does not decompress request bodies. Existing encodings, range responses, no-transform, private/no-store, Set-Cookie, SSE and gRPC are not transformed. Full-duplex activation before encoding preserves native streaming. Observed source/write failures abort instead of finalizing an incomplete encoded body. HEAD omits unknown representation lengths; upgrades retain the native writer. A malformed Accept-Encoding field is ignored and the response is not encoded.
func ContentSecurityPolicy ¶
func ContentSecurityPolicy(config CSPConfig) Middleware
ContentSecurityPolicy sets typed headers before the next handler, preserving the native writer and streaming interfaces. A nonce policy generates 256 random bits per request, places the nonce in context, and sets Cache-Control: no-store. Trusted downstream code can override headers; keep the rendered nonce and CSP together. Static policies do not change cache headers. Apply globally to include router failures. Foundry does not rewrite HTML or automatically allow inline code. Nested policies within the same request reuse its nonce, so an added report-only policy cannot invalidate the nonce already emitted by an enforced outer policy.
func CredentialRequests ¶
func CredentialRequests() Middleware
CredentialRequests protects credential submissions even when the response is empty or contains no issued secret. It requires POST and TLS (including an explicitly trusted proxy), sets no-store/no-cache before input decoding, and disables referrer disclosure. It does not replace CSRF, ingress rate limiting, credential verification or authorization. Browser routes also use CSRF.
func DefineMiddleware ¶
func DefineMiddleware(id MiddlewareID, construct func(stdhttp.Handler) (stdhttp.Handler, error)) Middleware
DefineMiddleware accepts a native net/http wrapper and its typed identity. The constructor may return a configuration error. It is not invoked until ApplyMiddleware or NewRouter assembles the handler chain.
func ETags ¶
func ETags(config ETagConfig) Middleware
ETags computes a validator for bounded, complete successful GET responses. HEAD and unsafe methods retain their native handler behavior. Streaming, overflow, existing validators, trailers, full-duplex I/O and large captures that cannot obtain capacity within AdmissionWait pass through without a validator. A body written once with its declared Content-Length (typed JSON) is hashed in place. A handler is executed once; this middleware does not cache response bodies.
func Locale ¶
func Locale(catalog *i18n.Catalog) Middleware
Locale resolves the request's explicit context preference or Accept-Language against one immutable catalog and localizes shared error responses. Those responses set Content-Language and Vary; successful responses retain their own representation policy. No catalog or services are stored in context.
func LocaleWith ¶
func LocaleWith(catalog *i18n.Catalog, negotiation LocaleNegotiation) Middleware
LocaleWith is Locale with explicit query, cookie and application sources. Responses selected by a query, cookie or user preference also depend on those inputs; keep such responses private or declare their cache variation.
func PublicURLs ¶
func PublicURLs(config PublicURLConfig) Middleware
PublicURLs validates the request origin and binds an approved base for typed route URL generation. Run after TrustedProxy when using forwarded authorities; ApplyMiddleware rejects the reverse order. Unknown/malformed origins return a shared 400 before handlers execute, except on ExemptPaths. This middleware leaves native Host, URL, TLS, headers, writer and routing unchanged.
func RateLimit ¶
func RateLimit[K any](limiter ratelimit.Limiter[K], key func(*stdhttp.Request) (K, error)) Middleware
RateLimit admits one unit using a concrete resource key. The limiter owns key resolution, its deadline and concurrency slot. Backend failures return the shared 503 error; confirmed quota exhaustion returns 429 with Retry-After and the X-RateLimit-* headers. Reusing a declaration shares quota across routes; use distinct declarations to scope quotas independently.
func RateLimitByActor ¶
func RateLimitByActor[M model.Identifiable](limiter ratelimit.Limiter[ActorKey], guard auth.Guard[M]) Middleware
RateLimitByActor keys a quota by the authenticated model, so users behind one address do not share a budget and one user cannot escape it by changing address. Anonymous requests on optional routes fall back to the client IP (IPv4 per address, IPv6 per /64). Install it with WithActorMiddleware: before authentication there is no scope, and the request fails instead of silently falling back to IP limiting.
func RateLimitByActorWith ¶
func RateLimitByActorWith[M model.Identifiable](limiter ratelimit.Limiter[ActorKey], guard auth.Guard[M], options IPRateLimitOptions) Middleware
RateLimitByActorWith sets the anonymous fallback's IP grouping.
func RateLimitByIP ¶
func RateLimitByIP(limiter ratelimit.Limiter[netip.Addr]) Middleware
RateLimitByIP uses Foundry attribution, falling back to the direct peer. IPv4 is keyed per address and IPv6 per /64; use RateLimitByIPWith to change the grouping. Install TrustedProxy before (outside) this middleware when trusted forwarded attribution is needed; ApplyMiddleware rejects the reverse order. It never parses forwarded headers itself. IPs are unmapped and zone-free.
func RateLimitByIPWith ¶
func RateLimitByIPWith(limiter ratelimit.Limiter[netip.Addr], options IPRateLimitOptions) Middleware
RateLimitByIPWith keys the quota by the client's masked network address.
func RequirePublicURLs ¶
func RequirePublicURLs() Middleware
RequirePublicURLs declares that a route generates public URLs. Place it on the route, inside any route-level PublicURLs. ApplyMiddleware rejects a router whose marked or signed routes are not covered by PublicURLs in the same chain or on the route; a router served without ApplyMiddleware fails the request with a shared 500 instead of inferring an origin from the request Host.
func SecurityHeaders ¶
func SecurityHeaders(config SecurityHeadersConfig) Middleware
SecurityHeaders snapshots configuration and supplies headers before routing or handler execution. Apply it globally to include router error responses. It preserves the native ResponseWriter and optional interfaces. Subsequent handlers may deliberately override these defaults; this is not a response filter that rewrites already-committed headers or buffers a streamed body.
func StatementDetector ¶
func StatementDetector(detector *database.StatementDetector, logger *slog.Logger) Middleware
StatementDetector begins a scope per request and logs redacted shape violations after the handler returns. Install the same detector on the database pools. Example: builder.Use(http.StatementDetector(detector,logger)).
func TrustedProxy ¶
func TrustedProxy(config TrustedProxyConfig) Middleware
TrustedProxy snapshots configuration and resolves client IP and declared origin metadata before invoking the next handler. Apply it globally before rate limits or authentication use request attribution. Native RemoteAddr, Host, URL, headers and TLS are unchanged. Unusable client-IP entries (unknown, obfuscated or malformed hops, including ip:port spellings it cannot parse) stop traversal at the last trusted hop with no fallback to a lower-priority header; they never reject the request. Invalid origin data at the trusted boundary still produces a shared 400 response.
func VerifyWebhook ¶
func VerifyWebhook[A any](verifier *webhook.Verifier[A]) Middleware
VerifyWebhook verifies before typed decoding and every idempotent replay. It replaces any caller-supplied Idempotency-Key with a digest of the authenticated provider and delivery ID. The endpoint must scope effects to the typed account from verifier.FromContext; distinct accounts must have separate endpoint keys.
func (Middleware) ID ¶
func (m Middleware) ID() MiddlewareID
ID returns the middleware's declared identifier.
func (Middleware) PreservesIdempotentResponses ¶
func (m Middleware) PreservesIdempotentResponses() Middleware
PreservesIdempotentResponses explicitly attests a custom wrapper's contract: it may reject before execution or change transport/security headers, but must preserve downstream application status/body/declared replay headers, must not issue cookies/credentials, and must not execute a request more than once. Compression of the stored application representation is permitted. Arbitrary wrappers outside Foundry's assembly remain their caller's responsibility.
func (Middleware) Validate ¶
func (m Middleware) Validate() error
Validate requires a semantic identifier and middleware constructor.
type MiddlewareID ¶
type MiddlewareID string
MiddlewareID is the semantic identity of one middleware declaration. It is distinct from route IDs and retained in route inspection metadata.
const BrowserSessionMiddlewareID MiddlewareID = "foundry.browser-session"
const CORSMiddlewareID MiddlewareID = "foundry.cors"
CORSMiddlewareID is the built-in policy's identity for middleware inspection.
const CSPMiddlewareID MiddlewareID = "foundry.content-security-policy"
CSPMiddlewareID identifies the typed content-security-policy middleware.
const CSRFMiddlewareID MiddlewareID = "foundry.csrf"
const CacheControlMiddlewareID MiddlewareID = "foundry.cache-control"
CacheControlMiddlewareID identifies the built-in response cache policy.
const CompressionMiddlewareID MiddlewareID = "foundry.compression"
const CredentialRequestsMiddlewareID MiddlewareID = "foundry.credential-requests"
const ETagMiddlewareID MiddlewareID = "foundry.etag"
const ImpersonationRefusalMiddlewareID MiddlewareID = "foundry.impersonation-refusal"
ImpersonationRefusalMiddlewareID identifies RefuseImpersonation.
const LocaleMiddlewareID MiddlewareID = "foundry.locale"
LocaleMiddlewareID identifies built-in request locale selection.
const PasswordConfirmationMiddlewareID MiddlewareID = "foundry.password-confirmation"
PasswordConfirmationMiddlewareID identifies RequirePasswordConfirmation.
const PublicURLMiddlewareID MiddlewareID = "foundry.public-url"
const PublicURLRequiredMiddlewareID MiddlewareID = "foundry.public-url-required"
PublicURLRequiredMiddlewareID marks a route that generates public URLs.
const SecurityHeadersMiddlewareID MiddlewareID = "foundry.security-headers"
SecurityHeadersMiddlewareID identifies the built-in response-default policy.
const StatementDetectorMiddlewareID MiddlewareID = "foundry.database.statement_shapes"
StatementDetectorMiddlewareID identifies the opt-in per-request N+1 diagnostic.
const TrustedProxyMiddlewareID MiddlewareID = "foundry.trusted-proxy"
TrustedProxyMiddlewareID identifies the built-in client-IP policy.
type Multipart ¶
type Multipart[B any] struct { // contains filtered or unexported fields }
Multipart binds declared form parts to one concrete request DTO. Text parts reuse typed URL scalar codecs; JSON parts reuse explicit JSON contracts. File parts retain request-owned UploadedFile handles. No model becomes a DTO. The zero descriptor is invalid. Generated forms use these same declarations.
func DefineMultipart ¶
func DefineMultipart[B any](parts ...MultipartPart[B]) Multipart[B]
DefineMultipart snapshots exact case-sensitive wire names. Repeated parts use the same literal name; brackets and dots do not imply nested objects.
func MultipartDirectory ¶ added in v0.2.0
MultipartDirectory configures a server-owned absolute directory. Empty uses the operating system's temporary directory. Assembly performs no file I/O; each request lazily creates a private directory inside this configured root.
type MultipartError ¶
type MultipartError struct {
// contains filtered or unexported fields
}
MultipartError reports bounded field diagnostics without submitted names, filenames, values or reader errors in its public text. Paths are JSON Pointers over declared form names, including repeated-part indexes where applicable.
func (*MultipartError) Error ¶
func (*MultipartError) Error() string
Error returns a generic multipart failure message without exposing input.
func (*MultipartError) GoString ¶
func (e *MultipartError) GoString() string
GoString returns the generic multipart failure message.
func (*MultipartError) Is ¶
func (*MultipartError) Is(target error) bool
Is reports whether target is fault.Invalid.
func (*MultipartError) Issues ¶
func (e *MultipartError) Issues() []contract.Issue
Issues returns a copy of the multipart validation issues.
func (*MultipartError) Unwrap ¶
func (e *MultipartError) Unwrap() error
Unwrap returns the underlying cause.
type MultipartInfo ¶
type MultipartInfo struct {
Parts []MultipartPartInfo `json:"parts"`
}
MultipartInfo describes the declared parts of a multipart request.
func InspectMultipart ¶ added in v0.2.0
func InspectMultipart[B any](d Multipart[B]) (MultipartInfo, error)
InspectMultipart returns owned metadata from the codecs used for actual decoding. Files are explicit multipart values and do not acquire a JSON model schema.
type MultipartKind ¶
type MultipartKind string
MultipartKind identifies each declared part's transport representation.
const ( MultipartText MultipartKind = "text" MultipartFile MultipartKind = "file" MultipartJSON MultipartKind = "json" )
type MultipartLimits ¶
type MultipartLimits struct {
Bytes, FileBytes int64
Parts, Files, Readers int
HeaderBytes, FieldBytes, FieldsBytes, Issues int
}
MultipartLimits bounds the complete encoded body, individual files, buffered non-file fields, part counts and simultaneously open uploaded-file readers. Bytes includes MIME framing and headers. FieldsBytes bounds retained text and JSON bytes together; JSON parts additionally use EndpointLimits.Body's depth, node, step and issue limits. The standard MIME parser also owns its header limits; HeaderBytes bounds accepted normalized part headers after parsing, not the native parser's allocation before that check.
func DefaultMultipartLimits ¶
func DefaultMultipartLimits() MultipartLimits
DefaultMultipartLimits returns upload, part, reader, header, field and issue bounds derived from default server settings.
func (MultipartLimits) Validate ¶
func (l MultipartLimits) Validate() error
Validate checks positive multipart resource bounds and their size and count relationships.
type MultipartPart ¶
type MultipartPart[B any] struct { // contains filtered or unexported fields }
MultipartPart declares one typed text, JSON or file field. Selectors must select only their field on the supplied DTO, without retaining or sharing it. All selector execution is owned by the request until it actually finishes.
func FilePart ¶
func FilePart[B any](name string, field func(*B) *UploadedFile) MultipartPart[B]
FilePart requires one file part, including an explicitly uploaded empty file. Use file validation to require nonempty contents; presence is independent.
func JSONPart ¶
func JSONPart[B, V any](name string, descriptor contract.JSON[V], field func(*B) *V) MultipartPart[B]
JSONPart requires one application/json part decoded by its declared contract. JSON nullability belongs to that concrete value's descriptor, independently of whether the multipart field is required or optional.
func OptionalFilePart ¶
func OptionalFilePart[B any](name string, field func(*B) *value.Optional[UploadedFile]) MultipartPart[B]
OptionalFilePart distinguishes omission from a supplied zero-byte file.
func OptionalJSONPart ¶
func OptionalJSONPart[B, V any](name string, descriptor contract.JSON[V], field func(*B) *value.Optional[V]) MultipartPart[B]
OptionalJSONPart preserves omission separately from a present JSON value, including explicit null when V's declared JSON contract supports it.
func RepeatedFilePart ¶
func RepeatedFilePart[B any, S ~[]UploadedFile](name string, field func(*B) *S) MultipartPart[B]
RepeatedFilePart preserves request order in an ordinary or named slice. An omitted field produces nil; a present empty file is one element.
func RepeatedJSONPart ¶
func RepeatedJSONPart[B, V any, S ~[]V](name string, descriptor contract.JSON[V], field func(*B) *S) MultipartPart[B]
RepeatedJSONPart decodes each same-named JSON part into one slice element.
func TextPart ¶
func TextPart[B any](parameter QueryParameter[B]) MultipartPart[B]
TextPart reuses an ordinary required, optional, repeated or default query parameter's codec and field selector. Raw form text is not URL-unescaped.
func (MultipartPart[B]) WithPresentation ¶
func (p MultipartPart[B]) WithPresentation(presentation contract.Presentation) MultipartPart[B]
WithPresentation attaches public hints to the declared multipart value. Only file parts accept FilePresentation; JSON parts retain their own schema.
type MultipartPartInfo ¶
type MultipartPartInfo struct {
QueryParameterInfo
Kind MultipartKind `json:"kind"`
Schema *contract.Schema `json:"schema,omitempty"`
}
MultipartPartInfo shares scalar/cardinality metadata with query bindings. Scalar and DefaultURL apply only to text parts; JSON parts supply Schema. A file has neither a scalar codec nor a JSON schema.
type NoContent ¶
type NoContent struct{}
NoContent is the concrete return value of an empty response handler.
type NoPath ¶
type NoPath struct{}
NoPath is the concrete parameter type for routes without URL parameters.
type NoQuery ¶
type NoQuery struct{}
NoQuery is the concrete type of an endpoint that accepts no query parameters.
type OptionalAuthenticationEndpoint ¶
type OptionalAuthenticationEndpoint[P, Q, B, M, R any] struct { // contains filtered or unexported fields }
OptionalAuthenticationEndpoint retains an explicit Optional model. Only absent credentials permit an anonymous handler; invalid/pending credentials fail.
func AuthorizeOptionalActor ¶ added in v0.2.0
func AuthorizeOptionalActor[P, Q, B, M, R any](e OptionalAuthenticationEndpoint[P, Q, B, M, R], authorize func(context.Context, value.Optional[M], Input[P, Q, B]) error) OptionalAuthenticationEndpoint[P, Q, B, M, R]
AuthorizeOptionalActor preserves the explicit absent-actor case. Invalid supplied credentials still fail admission before this optional-actor callback runs.
func ConfigureOptional ¶ added in v0.2.0
func ConfigureOptional[P, Q, B, M, R any](endpoint OptionalAuthenticationEndpoint[P, Q, B, M, R], options ...ActorOption[M]) OptionalAuthenticationEndpoint[P, Q, B, M, R]
ConfigureOptional applies actor options to a copy of endpoint, retaining missing-option errors for validation.
func OptionalAuthentication ¶
func OptionalAuthentication[P, Q, B, M, R any](endpoint Endpoint[P, Q, B, R], authentication *Authentication, guard auth.Guard[M], options ...ActorOption[M]) OptionalAuthenticationEndpoint[P, Q, B, M, R]
OptionalAuthentication adds an optional concrete subject to endpoint; invalid supplied credentials still fail authentication.
func OptionallyAuthenticated ¶
func OptionallyAuthenticated[P, Q, B, M, R any](endpoint Endpoint[P, Q, B, R], binding GuardBinding[M], options ...ActorOption[M]) OptionalAuthenticationEndpoint[P, Q, B, M, R]
OptionallyAuthenticated adds the bound guard's optional concrete subject and applies actor options to endpoint.
func PrepareOptional ¶ added in v0.2.0
func PrepareOptional[P, Q, B, M, R any](e OptionalAuthenticationEndpoint[P, Q, B, M, R], prepare Preparation[P, Q, B]) OptionalAuthenticationEndpoint[P, Q, B, M, R]
PrepareOptional returns an endpoint with the supplied request preparation callback.
func (OptionalAuthenticationEndpoint[P, Q, B, M, R]) Handle ¶
func (e OptionalAuthenticationEndpoint[P, Q, B, M, R]) Handle(handler func(context.Context, value.Optional[M], Input[P, Q, B]) (R, error)) RouteRegistration
Handle registers a typed callback receiving the guard's optional concrete subject.
type OptionalAuthenticationRoute ¶
type OptionalAuthenticationRoute[P, M any] struct { // contains filtered or unexported fields }
OptionalAuthenticationRoute distinguishes absent credentials from failed credentials with value.Optional[M]. Only absent credentials reach it anonymously.
func ConfigureOptionalRoute ¶ added in v0.2.0
func ConfigureOptionalRoute[P, M any](route OptionalAuthenticationRoute[P, M], options ...ActorOption[M]) OptionalAuthenticationRoute[P, M]
ConfigureOptionalRoute applies actor options to a copy of route, retaining missing-option errors for validation.
func OptionalRouteAuthentication ¶
func OptionalRouteAuthentication[P, M any](route Route[P], authentication *Authentication, guard auth.Guard[M], options ...ActorOption[M]) OptionalAuthenticationRoute[P, M]
OptionalRouteAuthentication adds optional typed authentication and actor options to a raw route.
type Origin ¶
type Origin string
Origin is an HTTP(S) origin without a path, credentials, query or fragment. Declarations may use ASCII hostnames, including punycode, or IP literals. ParseOrigin canonicalizes hostname casing, IP literals and default ports.
const NullOrigin Origin = "null"
NullOrigin explicitly permits the serialized opaque-origin value "null".
func ParseOrigin ¶
ParseOrigin validates a declaration and returns its normalized authority. It does not resolve DNS or convert Unicode hostnames to ASCII.
func PublicOrigin ¶
PublicOrigin returns the approved (possibly canonical) URL base. Its absence is explicit: the framework never falls back to an arbitrary request Host.
func RequestOrigin ¶
RequestOrigin returns the actual scheme/authority after trusted proxy handling. It does not apply a canonical URL override or prove host admission. Use PublicURLs middleware to constrain public hosts where required.
type OriginPattern ¶
type OriginPattern string
OriginPattern declares an additional browser origin that is not an exact HTTP(S) Origin: either an exact non-web origin serialized by an embedded webview or extension, such as capacitor://localhost, tauri://localhost or chrome-extension://<id>, or an HTTP(S) subdomain wildcard such as https://*.example.com (optionally with a port). A wildcard matches one or more complete labels before its suffix, never the bare suffix. Bare "*", partial-label wildcards, single-label suffixes and IP literals are rejected. Public-suffix knowledge is not built in; do not declare *.co.uk-style suffixes.
func (OriginPattern) Validate ¶
func (p OriginPattern) Validate() error
Validate checks that the origin pattern can be compiled.
func (OriginPattern) Wildcard ¶
func (p OriginPattern) Wildcard() bool
Wildcard reports whether the declaration matches a family of subdomains.
type Path ¶
type Path[P any] struct { // contains filtered or unexported fields }
Path owns a URL pattern and its concrete parameter bindings. Patterns use /users/{user} and an optional final {rest...}. Ordinary trailing slashes match exactly; use a named catch-all to match a subtree. There are no implicit raw parameter maps at call sites.
func DefinePath ¶
func DefinePath[P any](pattern string, parameters ...PathParameter[P]) Path[P]
DefinePath snapshots parameter declarations. Validation errors are reported at registration and URL generation so related descriptors can be declared as package variables. The pattern is parsed once, here.
func StaticPath ¶
StaticPath declares an exact path with no parameters.
type PathCodec ¶
type PathCodec[V any] interface { // Parse converts decoded path text to a typed value or returns a validation error. Parse(string) (V, error) // Format converts a typed path value to its textual representation before URL // escaping. Format(V) (string, error) }
PathCodec converts one decoded URL parameter to and from a concrete value. Implementations must be safe for concurrent use. Parse and Format must agree; neither receives escaped URL text. Path applies escaping exactly once.
func DescribeURL ¶
DescribeURL attaches an explicit same-value scalar contract to a custom path, query or cookie codec. Custom Parse/Format remain authoritative. An invalid descriptor or nil codec rejects binding; missing metadata is never guessed.
func EnumPath ¶
func EnumPath[E enum.Scalar, P PathTextPointer[E]](descriptor enum.Descriptor[E]) PathCodec[E]
EnumPath reuses the concrete enum descriptor for client metadata and its text methods for execution. Generation supplies the same enum's own descriptor.
func FloatPath ¶
FloatPath accepts finite decimal numbers, including scientific notation and signed zero. Parsing rounds to the concrete float width using strconv's nearest-value rules; underflow can round to zero. It rejects overflow, whitespace, hexadecimal literals, digit separators, NaN and infinity. Format emits the shortest decimal that round trips at that width. Use a text codec such as decimal.Decimal when decimal values must stay exact.
func IntegerPath ¶
func IntegerPath[V PathInteger]() PathCodec[V]
IntegerPath accepts decimal integers without plus signs, whitespace or leading zeroes. It checks the destination width before conversion, including named types.
func ModelIDPath ¶
ModelIDPath preserves model ownership when decoding and generating URLs. It rejects the nil UUID. Parsing is not a database lookup or authorization check.
func StringPath ¶
StringPath preserves ordinary and named string types. Path rejects empty single segments, controls, dot segments and a slash-only segment. A final catch-all can contain slashes and can be empty.
func TextPath ¶
func TextPath[V any, P PathTextPointer[V]]() PathCodec[V]
TextPath uses a type's existing text codec, including its validation. Generated enum membership, exact decimal and temporal representations keep their source of truth. Custom methods must be deterministic, respect input ownership and be safe for concurrent calls. Path catches panic/Goexit, waits for codec completion and validates the resulting text. Direct codec calls do not add that boundary. Known decimal/temporal types carry automatic metadata. Use EnumPath for enum case metadata, or DescribeURL to describe a custom type explicitly.
func URLType ¶
URLType supplies the source identity for an already-described scalar codec. Generated declarations use this boundary because executable main packages and their generic arguments cannot recover source import paths from reflection. It preserves V, the codec's syntax, scalar shape and native Parse/Format rules. Source IDs are owned by generation; custom authors must supply the actual source identity. Opaque codecs require DescribeURL before using this function.
type PathInteger ¶
type PathInteger interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64
}
PathInteger is the set of integer types supported by IntegerPath. Named integer types retain their identity through parsing, fields and URL generation.
type PathParameter ¶
type PathParameter[P any] struct { // contains filtered or unexported fields }
PathParameter binds a named URL parameter to a concrete field of P. Its callbacks are assembled by Param; there is no string-based field lookup.
func Param ¶
func Param[P, V any](name string, codec PathCodec[V], field func(*P) *V) PathParameter[P]
Param defines a field once for both decoding and named URL generation. The field selector must return the address of the selected field on its argument, be deterministic and be safe for concurrent calls with independent arguments. Generated path declarations can use this same public constructor.
func (PathParameter[P]) WithPresentation ¶
func (p PathParameter[P]) WithPresentation(presentation contract.Presentation) PathParameter[P]
WithPresentation attaches public hints to a typed path field. Path segments are URL components, so password hints are rejected.
type PathParameterInfo ¶
type PathParameterInfo struct {
Presentation contract.Presentation `json:"presentation,omitzero"`
Name string `json:"name"`
CatchAll bool `json:"catch_all"`
Scalar *URLScalarInfo `json:"scalar,omitempty"`
}
PathParameterInfo retains pattern order, catch-all semantics and an optional codec-owned scalar description. Nil Scalar identifies an undescribed custom codec; exporters must report that gap instead of inferring a string schema.
func PathParameters ¶ added in v0.2.0
func PathParameters[P any](p Path[P]) ([]PathParameterInfo, error)
PathParameters returns an owned description from the same path and field bindings used at execution. It does not inspect a request or call Parse/Format.
func RouteParameters ¶ added in v0.2.0
func RouteParameters[P any](r Route[P]) ([]PathParameterInfo, error)
RouteParameters exposes typed path metadata for either typed or raw routes. Raw payloads do not acquire inferred request/response DTOs.
type PathTextPointer ¶
type PathTextPointer[V any] interface { *V encoding.TextMarshaler encoding.TextUnmarshaler }
PathTextPointer is the pointer method set required by TextPath. It accepts both pointer and value marshal methods while retaining the concrete value V.
type PayloadInfo ¶
type PayloadInfo struct {
MediaType string `json:"media_type,omitempty"`
Schema contract.Schema `json:"schema,omitzero"`
Form []QueryParameterInfo `json:"form,omitempty"`
Multipart *MultipartInfo `json:"multipart,omitempty"`
File *FileResponseInfo `json:"file,omitempty"`
Raw *RawBodyInfo `json:"raw,omitempty"`
Example json.RawMessage `json:"example,omitempty"`
}
PayloadInfo describes the JSON, form, multipart or file contract used at runtime. EndpointInfo uses nil payload pointers for empty bodies/responses. Example is a documented JSON example already encoded by the same contract.
type PermissionDirective ¶
type PermissionDirective struct {
Feature PermissionFeature
Self bool
Any bool
Origins []Origin
}
PermissionDirective grants one feature to an allowlist. The zero allowlist disables the feature everywhere (feature=()). Any grants every origin (*) and excludes Self and Origins. Origins are exact HTTP(S) origins.
type PermissionFeature ¶
type PermissionFeature string
PermissionFeature names one Permissions-Policy feature. The constants cover common powerful features; other registered features use the same type and are validated as lowercase tokens.
const ( PermissionCamera PermissionFeature = "camera" PermissionMicrophone PermissionFeature = "microphone" PermissionGeolocation PermissionFeature = "geolocation" PermissionPayment PermissionFeature = "payment" PermissionUSB PermissionFeature = "usb" PermissionFullscreen PermissionFeature = "fullscreen" PermissionDisplayCapture PermissionFeature = "display-capture" PermissionClipboardWrite PermissionFeature = "clipboard-write" PermissionBrowsingTopics PermissionFeature = "browsing-topics" PermissionPublicKeyCreate PermissionFeature = "publickey-credentials-create" PermissionPublicKeyGet PermissionFeature = "publickey-credentials-get" )
type Preparation ¶
Preparation receives structurally decoded values and returns query/body values for validation. Path identity cannot be replaced. Treat input and all referenced data as borrowed and immutable; copy a slice/map before changing its contents. Do not perform business writes here. Defaults require Optional wire fields.
type ProxyHeader ¶
type ProxyHeader struct {
// contains filtered or unexported fields
}
ProxyHeader declares one forwarding source and its parser. Use the provided constructors; malformed data in the first present source never falls through to another header. Header priority is the order declared in TrustedProxyConfig.
func ClientIPHeader ¶
func ClientIPHeader(name HeaderName) ProxyHeader
ClientIPHeader selects one IP address from a header overwritten by a trusted peer, such as X-Real-IP or CF-Connecting-IP. It cannot parse chain headers.
func ForwardedHeader ¶
func ForwardedHeader() ProxyHeader
ForwardedHeader selects RFC 7239's Forwarded chain and its for parameters. Other parameters are parsed but do not rewrite request Host, URL or TLS state.
func XForwardedForHeader ¶
func XForwardedForHeader() ProxyHeader
XForwardedForHeader selects a comma-separated IP chain, walked right to left.
func (ProxyHeader) Name ¶
func (h ProxyHeader) Name() HeaderName
Name returns the declared forwarding header name.
func (ProxyHeader) Validate ¶
func (h ProxyHeader) Validate() error
Validate checks the header name against its single-IP or chain parser declaration.
type ProxyOriginHeader ¶
type ProxyOriginHeader struct {
// contains filtered or unexported fields
}
ProxyOriginHeader declares an origin source from an explicitly trusted peer. Use a constructor. First-present priority never falls through malformed data.
func ForwardedOriginHeader ¶
func ForwardedOriginHeader() ProxyOriginHeader
ForwardedOriginHeader selects host and proto from the same RFC 7239 element at the trusted chain boundary. Both parameters are required on that element. Unknown/missing for values stop traversal; earlier elements are never skipped.
func ProxyOriginHeaders ¶
func ProxyOriginHeaders(scheme, authority HeaderName) ProxyOriginHeader
ProxyOriginHeaders selects an overwritten single scheme/authority header pair. Use ForwardedOriginHeader when a multi-hop origin chain is required.
func ProxySchemeHeader ¶
func ProxySchemeHeader(scheme HeaderName) ProxyOriginHeader
ProxySchemeHeader selects one overwritten scheme header while preserving the native request Host. This is suitable when the proxy preserves the public Host.
func XForwardedOriginHeaders ¶
func XForwardedOriginHeaders() ProxyOriginHeader
XForwardedOriginHeaders uses one X-Forwarded-Proto and X-Forwarded-Host value. The trusted edge must overwrite both fields. Comma lists are rejected because independently appended X-Forwarded lists do not prove a shared hop boundary.
func (ProxyOriginHeader) Validate ¶
func (h ProxyOriginHeader) Validate() error
Validate checks the declared Forwarded, scheme or scheme-and-host header combination.
type PublicURLConfig ¶
type PublicURLConfig struct {
AllowedOrigins []Origin
AllowedPatterns []OriginPattern
Canonical value.Optional[Origin]
ExemptPaths []string
}
PublicURLConfig allows public request origins. Origins include scheme and port; no incoming Host is implicitly trusted. AllowedPatterns admits HTTP(S) subdomain wildcards such as https://*.example.com for tenant hosts; the admitted request origin itself becomes the URL base. Canonical, when set, must be allowed and supplies generated URLs for all accepted aliases. It does not redirect requests or change IsSecure's transport determination. ExemptPaths lists exact request paths, such as load-balancer or Kubernetes probes that arrive with Host: <pod-ip>, served without host admission. No public origin is bound for them, so they cannot generate public/signed URLs.
func (PublicURLConfig) Validate ¶
func (c PublicURLConfig) Validate() error
Validate checks that public URL origins and configuration can be compiled.
type Query ¶
type Query[Q any] struct { // contains filtered or unexported fields }
Query binds a query string to a concrete value without an untyped parameter map at the consumer boundary. DefineQuery snapshots its field declarations; the zero descriptor is invalid. Generated declarations use these same bindings.
func DefineQuery ¶
func DefineQuery[Q any](parameters ...QueryParameter[Q]) Query[Q]
DefineQuery declares exact, case-sensitive names. Brackets and dots in a name are literal characters, not implicit nesting. Declaration order does not affect encoding or field diagnostics. Call Validate during route registration.
func EmbedQuery ¶
EmbedQuery binds an existing query descriptor to a concrete field of an outer query value. Wire names, required/repeated behavior, defaults and scalar metadata remain owned by the original bindings; embedding adds no wire prefix. The selector must select a field of its argument, never retain it, and be safe for concurrent calls on independent arguments. It executes inside the same owned callback boundary as ordinary query field selectors.
func EmptyQuery ¶
EmptyQuery rejects any undeclared query key through the ordinary query codec.
func MergeQueries ¶
MergeQueries combines descriptors for the same concrete query type. It reuses their field bindings and metadata, rejects duplicate wire names, and preserves the ordinary strict query parser. No precedence is assigned to an overlapping parameter. An empty list defines a query with no parameters.
type QueryCodec ¶
QueryCodec converts one decoded query value. Query and path values share the same scalar conversion contract; their escaping and structural rules differ.
func BoolQuery ¶
func BoolQuery[V ~bool]() QueryCodec[V]
BoolQuery uses exactly true and false. A bare query key is not an implicit true.
func EnumQuery ¶
func EnumQuery[E enum.Scalar, P QueryTextPointer[E]](descriptor enum.Descriptor[E]) QueryCodec[E]
EnumQuery shares EnumPath's typed membership metadata and text conversion.
func FloatQuery ¶
func FloatQuery[V QueryFloat]() QueryCodec[V]
FloatQuery accepts finite decimal/scientific input at the concrete float width. Use a text codec such as decimal.Decimal for exact decimal representations.
func IntegerQuery ¶
func IntegerQuery[V QueryInteger]() QueryCodec[V]
IntegerQuery requires canonical decimal input and preserves the integer width.
func ModelIDQuery ¶
func ModelIDQuery[M any]() QueryCodec[model.ID[M]]
ModelIDQuery preserves model ownership and rejects an empty model identity. Parsing is not a database lookup or an authorization check.
func StringQuery ¶
func StringQuery[V ~string]() QueryCodec[V]
StringQuery preserves text, including spaces and explicit empty values.
func TextQuery ¶
func TextQuery[V any, P QueryTextPointer[V]]() QueryCodec[V]
TextQuery reuses the value's text methods, including generated enum membership validation and exact decimal/temporal representations. Custom methods must be deterministic, concurrency-safe and return owned values and bounded output.
type QueryError ¶
type QueryError struct {
// contains filtered or unexported fields
}
QueryError reports malformed transport input, an invalid field representation or invalid query output. Issues use JSON Pointer syntax over declared query names; unknown names report at the root and are never echoed. Error text never includes submitted names/values or custom codec messages. Causes are retained for deliberate internal inspection. Every failed Decode/Encode returns zero.
func (*QueryError) Error ¶
func (*QueryError) Error() string
Error returns a generic query failure message without exposing input.
func (*QueryError) GoString ¶
func (e *QueryError) GoString() string
GoString returns the generic query failure message.
func (*QueryError) Is ¶
func (*QueryError) Is(target error) bool
Is reports whether target is fault.Invalid.
func (*QueryError) Issues ¶
func (e *QueryError) Issues() []contract.Issue
Issues returns a copy of the query validation issues.
func (*QueryError) Unwrap ¶
func (e *QueryError) Unwrap() error
Unwrap returns the underlying cause.
type QueryFloat ¶
type QueryFloat = PathFloat
QueryFloat retains ordinary or named floating-point types through query binding.
type QueryInteger ¶
type QueryInteger = PathInteger
QueryInteger retains ordinary or named integer types through query binding.
type QueryLimits ¶
type QueryLimits struct{ Bytes, Pairs, Issues int }
QueryLimits bounds encoded bytes, parameter slots and returned diagnostics. All fields must be positive. HTTP endpoint adapters own their default limits.
func (QueryLimits) Validate ¶
func (l QueryLimits) Validate() error
Validate checks wire decoding bounds and requires a positive diagnostic issue limit.
type QueryParameter ¶
type QueryParameter[Q any] struct { // contains filtered or unexported fields }
QueryParameter binds one declared query name to a concrete field. Construct it with QueryParam, OptionalQueryParam or RepeatedQueryParam. Field selectors must select a field on the supplied argument and be safe for concurrent calls on independent arguments. They must not mutate any other field or retain it.
func DefaultQueryParam ¶
func DefaultQueryParam[Q, V any](name string, codec QueryCodec[V], defaultValue V, field func(*Q) *V) QueryParameter[Q]
DefaultQueryParam uses a declared value only when the query key is omitted. Explicit zero, false and empty input still pass through the codec. Duplicate keys retain ordinary scalar rejection. Encoding always writes the actual field value; it does not silently omit values equal to the default.
Construction snapshots the default's canonical URL spelling through the supplied codec and checks its round trip before retaining it. Codec methods run inside an owned callback boundary and must finish. Each omitted decode parses that immutable spelling afresh, so defaults do not share mutable field values across requests. Metadata exposes the same spelling as DefaultURL; defaults are public declaration data.
func OptionalQueryParam ¶
func OptionalQueryParam[Q, V any](name string, codec QueryCodec[V], field func(*Q) *value.Optional[V]) QueryParameter[Q]
OptionalQueryParam distinguishes omission from an explicitly supplied zero or empty value. Query strings have no implicit database/JSON null literal.
func QueryParam ¶
func QueryParam[Q, V any](name string, codec QueryCodec[V], field func(*Q) *V) QueryParameter[Q]
QueryParam requires exactly one value, including its explicit zero or empty representation. A duplicate scalar key is rejected before any codec executes.
func RepeatedQueryParam ¶
func RepeatedQueryParam[Q, V any, S ~[]V](name string, codec QueryCodec[V], field func(*Q) *S) QueryParameter[Q]
RepeatedQueryParam binds repeated keys to an ordinary or named slice. An omitted key produces nil; a present empty value is one item for the codec to parse. Nil and empty slices both encode as omission. Item order is preserved.
func (QueryParameter[Q]) WithPresentation ¶
func (p QueryParameter[Q]) WithPresentation(presentation contract.Presentation) QueryParameter[Q]
WithPresentation attaches bounded public display metadata to this binding. The codec and requiredness remain authoritative; contradictory hints fail registration. No submitted value is inspected or exported.
type QueryParameterInfo ¶
type QueryParameterInfo struct {
Presentation contract.Presentation `json:"presentation,omitzero"`
Scalar *URLScalarInfo `json:"scalar,omitempty"`
Name string `json:"name"`
Required bool `json:"required"`
Repeated bool `json:"repeated"`
// DefaultURL is an unescaped URL scalar spelling, not a JSON default value.
// Absence differs from a present empty-string default.
DefaultURL value.Optional[string] `json:"default_url,omitzero"`
}
QueryParameterInfo describes cardinality and codec metadata without inspecting values. Repeated fields use repeated keys, never implicit comma or bracket expansion.
func QueryParameters ¶ added in v0.2.0
func QueryParameters[Q any](d Query[Q]) ([]QueryParameterInfo, error)
QueryParameters returns an owned, deterministic snapshot of cardinality and scalar metadata.
type QueryTextPointer ¶
type QueryTextPointer[V any] = PathTextPointer[V]
QueryTextPointer is the complete text codec of the concrete value V.
type RawBody ¶
type RawBody struct {
// contains filtered or unexported fields
}
RawBody is a typed endpoint's streaming request body of a declared media type. The handler reads it; nothing is buffered in advance. Reads are bounded by EndpointLimits.Raw.Bytes and the route's body limit. Read errors are framework errors a handler may return as-is: an oversized body is 413, a client that sends too slowly is 408 and a broken transfer is 400. The body closes when the handler returns. Preparation, authorization and validation receive it too, but must not read it.
func (RawBody) MarshalJSON ¶
MarshalJSON rejects implicit serialization; a raw body is not a JSON value.
type RawBodyInfo ¶
type RawBodyInfo struct {
MediaTypes []MediaType `json:"media_types"`
}
RawBodyInfo describes a raw request body's accepted media types.
type RawBodyLimits ¶
type RawBodyLimits struct {
Bytes int64
}
RawBodyLimits bounds a raw request body. The route's WithBodyLimit (or the kernel MaxBodyBytes) still applies; raise both for large uploads. A zero value is allowed on endpoints without a raw body.
func (RawBodyLimits) Validate ¶
func (l RawBodyLimits) Validate() error
Validate requires a positive byte limit no greater than MaxRouteBodyBytes.
type RawHandler ¶
type RawHandler[P any] func(stdhttp.ResponseWriter, *stdhttp.Request, P)
RawHandler receives decoded, concrete path parameters and native transport objects. Request bodies and responses remain explicit application responsibilities and are not typed client schemas. RequireRouteAuthentication supplies a verified concrete subject without changing these native payload boundaries.
type Redirect ¶
type Redirect struct {
// contains filtered or unexported fields
}
Redirect is a typed endpoint's validated redirect target on this origin. Build it with RedirectTo, RedirectToRoute or RedirectToEndpoint; its zero value is invalid. A redirect never follows request input to another host.
func RedirectTo ¶
RedirectTo accepts a relative URL on this origin: a path starting with one "/" (never "//" or "/\", which browsers read as another host), with an optional query and fragment, in printable ASCII without spaces or backslashes. Absolute and scheme-relative URLs are rejected, so request input cannot produce an open redirect. Prefer RedirectToRoute for named routes.
func RedirectToEndpoint ¶
func RedirectToEndpoint[P, Q, B, R any](ctx context.Context, endpoint Endpoint[P, Q, B, R], path P, query Q) Redirect
RedirectToEndpoint redirects to a typed endpoint's URL generated from its concrete path and query.
func RedirectToRoute ¶
RedirectToRoute redirects to a named route's URL generated from its concrete path.
func (Redirect) MarshalJSON ¶
MarshalJSON rejects implicit serialization; a redirect has no body contract.
type ReferrerPolicy ¶
type ReferrerPolicy string
ReferrerPolicy selects a single standard Referrer-Policy token. Zero omits the header. The type remains distinct from frame and custom-header values.
const ( ReferrerNoReferrer ReferrerPolicy = "no-referrer" ReferrerNoReferrerWhenDowngrade ReferrerPolicy = "no-referrer-when-downgrade" ReferrerSameOrigin ReferrerPolicy = "same-origin" ReferrerOrigin ReferrerPolicy = "origin" ReferrerStrictOrigin ReferrerPolicy = "strict-origin" ReferrerOriginWhenCrossOrigin ReferrerPolicy = "origin-when-cross-origin" ReferrerStrictOriginWhenCrossOrigin ReferrerPolicy = "strict-origin-when-cross-origin" ReferrerUnsafeURL ReferrerPolicy = "unsafe-url" )
func (ReferrerPolicy) Validate ¶
func (p ReferrerPolicy) Validate() error
Validate accepts an omitted or supported referrer policy.
type RefreshCookie ¶
type RefreshCookie struct {
// contains filtered or unexported fields
}
RefreshCookie names the HttpOnly cookie that carries a browser client's refresh token, so JavaScript never reads it. Its attributes are fixed: the __Host- prefix (host-only, Path=/), Secure, HttpOnly and SameSite=Strict. Every endpoint that sets, reads or clears it requires POST, TLS (or a configured TrustedProxy), no-store and its origin protection. Give each guard its own name when several portals share one origin. Construction performs no I/O.
func DefineRefreshCookie ¶
func DefineRefreshCookie(name CookieName, csrf CSRFConfig) RefreshCookie
DefineRefreshCookie declares a Secure, HttpOnly, SameSite=Strict refresh cookie at / with CSRF protection. Validate requires a __Host- name.
func (RefreshCookie) Name ¶
func (c RefreshCookie) Name() CookieName
Name returns the refresh cookie's declared name.
func (RefreshCookie) Validate ¶
func (c RefreshCookie) Validate() error
Validate checks retained declaration errors and requires a compiled CSRF policy.
type RefreshCookieInfo ¶
type RefreshCookieInfo struct {
Name CookieName `json:"name"`
Reads bool `json:"reads,omitempty"`
Sets bool `json:"sets,omitempty"`
Clears bool `json:"clears,omitempty"`
Optional bool `json:"optional,omitempty"`
}
RefreshCookieInfo describes an endpoint's refresh-cookie use for contract export: whether it reads the refresh credential from the cookie, sets it on success, or clears it on success. An endpoint that reads it also clears it in a 401 response, and must set or clear it on success: the read credential is consumed, so leaving it in the browser would turn the next refresh into a replay. It never contains a credential value.
Optional marks a cookie-authenticated logout: it reads the cookie when the browser has one and succeeds, clearing it, when it does not.
func (RefreshCookieInfo) Validate ¶
func (i RefreshCookieInfo) Validate() error
Validate checks the __Host- name and supported read, set, clear and optional metadata combinations.
type RefreshCookieLogoutRequest ¶
type RefreshCookieLogoutRequest struct {
RefreshToken value.Optional[RefreshCredential]
}
RefreshCookieLogoutRequest is a cookie-authenticated logout's input: the refresh credential, when the browser presented a well-formed cookie.
type RefreshCredential ¶
type RefreshCredential = authtransport.RefreshCredential
RefreshCredential is the validated, redacted value in RefreshTokenRequest. Secret() explicitly permits using it for a token operation.
type RefreshTokenRequest ¶
type RefreshTokenRequest = authtransport.RefreshRequest
RefreshTokenRequest is Foundry's refresh input. RefreshToken retains a redacted credential; pass its Secret() directly to Tokens.Refresh. It comes from the JSON body (RefreshTokenBody) or, for browser clients, only from the HttpOnly refresh cookie (RefreshTokenCookie); never from URL parameters.
type RequestAuthorization ¶
RequestAuthorization runs after preparation and before validation, handler or model-binding work, as a Laravel FormRequest authorizes before its rules. A denied caller never reaches database-backed rules such as Unique or Exists. It receives structurally decoded, prepared input that validation has not yet checked. Return a declared HTTP error to deny the request safely.
type RequestEvent ¶
type RequestEvent struct {
RequestID attribution.RequestID
Method Method
Route RouteID
Result observability.Result
Duration time.Duration
Bytes int64
Hijacked bool
}
RequestEvent is a metadata-only completion snapshot. It deliberately excludes raw paths/queries, headers, bodies, credentials and error payloads. An empty Route means no declared route matched. Hijacked records the HTTP handoff only.
type RequestMetric ¶
type RequestMetric struct {
Route RouteID
Method Method
Result observability.Result
Count uint64
Seconds float64
Buckets []uint64
}
RequestMetric is a route/method/status series with cumulative duration buckets. Only declared routes enter labels; an unmatched route is the empty category.
type RequestMetrics ¶
type RequestMetrics struct {
// contains filtered or unexported fields
}
RequestMetrics has a fixed series bound and no per-request I/O. Drain returns an owned interval snapshot and resets counters under the same lock as Observe.
func NewRequestMetrics ¶
func NewRequestMetrics(maxSeries int) (*RequestMetrics, error)
NewRequestMetrics creates a mutex-protected collector with a series bound between one and 4096.
func (*RequestMetrics) Drain ¶
func (m *RequestMetrics) Drain() RequestMetricsSnapshot
Drain returns an owned metrics snapshot and resets the collector.
func (*RequestMetrics) ObserveRequest ¶
func (m *RequestMetrics) ObserveRequest(_ context.Context, event RequestEvent)
ObserveRequest records normalized duration metrics under bounded route, method and result labels, counting dropped series when capacity is full.
func (*RequestMetrics) Snapshot ¶
func (m *RequestMetrics) Snapshot() RequestMetricsSnapshot
Snapshot returns an owned metrics snapshot without resetting the collector.
func (*RequestMetrics) WritePrometheus ¶
func (m *RequestMetrics) WritePrometheus(w io.Writer) error
WritePrometheus exposes only bounded route metadata. Do not concurrently Drain a cumulative exporter: choose snapshots for scraping or drains for persistence.
type RequestMetricsSnapshot ¶
type RequestMetricsSnapshot struct {
Series []RequestMetric
Dropped uint64
}
RequestMetricsSnapshot contains request metric series and the number of observations dropped for new series.
type RequestObserver ¶
type RequestObserver interface {
// ObserveRequest receives a completed request's bounded metadata and outcome.
ObserveRequest(context.Context, RequestEvent)
}
RequestObserver runs once after handling (including rejection/abort), before request ownership is released. It must return; its context may be cancelled. Panics and Goexit are isolated. Use middleware for request/response behavior.
type RequestObserverFunc ¶
type RequestObserverFunc func(context.Context, RequestEvent)
RequestObserverFunc adapts a function to RequestObserver.
func (RequestObserverFunc) ObserveRequest ¶
func (f RequestObserverFunc) ObserveRequest(ctx context.Context, event RequestEvent)
ObserveRequest calls f with the request event.
type Response ¶
type Response[R any] struct { // contains filtered or unexported fields }
Response is a declared success payload and status. It retains the response DTO type at handler registration; its zero value is invalid.
func ClearRefreshCookie ¶
func ClearRefreshCookie[R any](cookie RefreshCookie, response Response[R]) Response[R]
ClearRefreshCookie returns response extended to clear the refresh cookie on success and in a 401 its handler returns, for a logout endpoint: a browser's RefreshTokenCookieLogout, or one calling Tokens.RevokeCurrent behind authentication. A 401 from the guard's authentication middleware runs before the endpoint and keeps the cookie, revoking nothing. The endpoint gains the cookie's request protections.
func DownloadResponse ¶
DownloadResponse retains Download as the handler's concrete result. At least one concrete media type is declared; every opened representation must match. The normal status is 200; native conditions and ranges can produce 206 or 304.
func EmptyResponse ¶
EmptyResponse supports 204 No Content and 205 Reset Content.
func EventStreamResponse ¶
EventStreamResponse declares a server-sent event (text/event-stream) response whose event data is typed by descriptor. The handler returns Events built by EventsFrom; the stream starts only after it succeeded, then behaves as ServeEvents (flush per event, heartbeats, bounded queue, owned producer). Each event's data is bounded by EndpointLimits.Response. Declare the route's WithTimeout for the longest stream lifetime. A client disconnect or the route deadline ends the stream normally; a producer failure or an invalid event aborts the connection. Metadata, OpenAPI and the TypeScript client describe the stream and its data type; the client iterates the decoded events.
func JSONResponse ¶
JSONResponse declares a success status with a schema-checked JSON payload.
func JSONResponses ¶
func JSONResponses[R any](descriptor contract.JSON[R], status int, alternatives ...int) Response[Statused[R]]
JSONResponses declares a JSON response with several success statuses, primary first, for example 200 and 201 for an upsert. The handler returns Statused[R] and selects one; zero selects status. Every status shares the descriptor. Selecting an undeclared status is an internal failure and publishes nothing. Metadata, OpenAPI and generated clients expose every declared status; the TypeScript client returns the received status with the decoded value. Idempotent endpoints require a single status, because a replay reproduces it.
func MFAEnrollmentResponse ¶
MFAEnrollmentResponse deliberately discloses a committed enrollment's secret and provisioning URI. Use after Factors.Enroll with current password verification. It requires secure POST and disables caching before the handler runs. Ordinary JSON of Enrollment never discloses these values. Failed HTTP delivery cannot undo enrollment; repeating Enroll replaces the unconfirmed generation.
func MFARecoveryResponse ¶
func MFARecoveryResponse[M any](status int) Response[mfa.RecoveryCodes[M]]
MFARecoveryResponse explicitly delivers the recovery set returned by Confirm or RegenerateRecovery through secure POST/no-store. It exposes no model, proof or credential. A lost response requires a new factor-authorized regeneration; the framework never stores recoverable plaintext codes for later retrieval.
func RedirectResponse ¶
RedirectResponse declares a redirect with status 301, 302, 303, 307 or 308 and no body; for example 303 after a browser form submission. The handler returns a Redirect. Metadata and OpenAPI describe the Location header, and the TypeScript client returns the location instead of following it.
func StreamResponse ¶
StreamResponse keeps the handler result typed as Stream. Declared media, byte limits and owned metadata share DownloadResponse's file contract. Ranges are ignored and Accept-Ranges is none; no validator is fabricated.
func TicketResponse ¶
TicketResponse delivers a single-use WebSocket handshake ticket from Tokens.IssueTicket through the same explicit credential boundary as TokenResponse: POST, TLS (or a configured TrustedProxy), no-store, and no delivery after the request ended. Mount it behind the issuing binding's guard. The body is {"ticket": ..., "expires_in": seconds}. The clock must agree with the token backend. Construction performs no I/O.
func TokenCookieResponse ¶
func TokenCookieResponse[M, K any](cookie RefreshCookie, status int, source clock.Clock) Response[token.Issued[M, K]]
TokenCookieResponse delivers an issuance for a browser client. The JSON body carries only the access token ({"tokens": {"access_token", "expires_in", "token_type"}, "mfa_required"}); a renewable token's refresh secret is set in the refresh cookie, expiring at the family's refresh-idle deadline, and is set again on every rotation. It keeps every TokenResponse safeguard and adds the cookie's origin protection, which also prevents login CSRF. Personal and MFA-pending credentials set no cookie. The clock must agree with the backend.
func TokenResponse ¶
TokenResponse delivers a model-owned issuance through an explicit credential boundary. Handlers return token.Issued directly. Ordinary JSON of Issued stays redacted. The endpoint requires POST and TLS (or a configured TrustedProxy), disables caching, and checks access expiry before preparing its bounded JSON. The clock must agree with the token backend. Construction performs no I/O. A committed credential cannot be atomically delivered over HTTP: failed or uncertain delivery must not retry issuance/refresh automatically.
type ResponseHeader ¶
type ResponseHeader struct {
Name HeaderName
Value HeaderValue
}
ResponseHeader is one explicit, typed native response-header declaration. SecurityHeaders validates names/values and rejects duplicates and framing headers; it does not infer header-specific semantics from arbitrary strings.
func EndpointLocation ¶
func EndpointLocation[P, Q, B, R any](ctx context.Context, endpoint Endpoint[P, Q, B, R], path P, query Q) (ResponseHeader, error)
EndpointLocation returns a Location header for a typed endpoint's relative URL, generated from its concrete path and query types.
func RouteLocation ¶
func RouteLocation[P any](route Route[P], path P) (ResponseHeader, error)
RouteLocation returns a Location header for a named route's relative URL, generated from its concrete path type, for use with WithHeaders.
func (ResponseHeader) Validate ¶
func (h ResponseHeader) Validate() error
Validate checks the header's name and value.
type ResponseHeaders ¶
type ResponseHeaders[R any] func(context.Context, R) ([]ResponseHeader, error)
ResponseHeaders derives response metadata from a handler's successful result.
type Route ¶
type Route[P any] struct { // contains filtered or unexported fields }
Route binds a semantic endpoint identity and method to concrete path parameters. Reuse the same descriptor for registration and URL generation.
func ConfigureRoute ¶ added in v0.2.0
func ConfigureRoute[P any](route Route[P], options ...RouteOption) Route[P]
ConfigureRoute applies declaration options to a copy of route and retains missing-option errors for validation.
func DefineRoute ¶
func DefineRoute[P any](spec RouteSpec, path Path[P], options ...RouteOption) Route[P]
DefineRoute declares a typed path route and applies its options; validation occurs separately.
type RouteDocumentation ¶
type RouteDocumentation struct {
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
Tags []string `json:"tags,omitempty"`
Deprecated bool `json:"deprecated,omitempty"`
}
RouteDocumentation is human-facing API documentation exported with client contracts, OpenAPI and TypeScript comments. It never changes matching, access, limits or runtime behavior; the route ID remains the operation ID.
func (RouteDocumentation) Validate ¶
func (d RouteDocumentation) Validate() error
Validate checks text bounds and rejects empty or duplicate tags.
type RouteID ¶
type RouteID string
RouteID is the stable semantic identity used by inspection and client contracts.
func AuthenticatedEndpointID ¶ added in v0.2.0
func AuthenticatedEndpointID[P, Q, B, M, R any](endpoint AuthenticatedEndpoint[P, Q, B, M, R]) RouteID
AuthenticatedEndpointID returns the endpoint's route identifier.
func EndpointID ¶ added in v0.2.0
EndpointID returns the endpoint's declared route identifier.
func IdempotentEndpointID ¶ added in v0.2.0
func IdempotentEndpointID[P, Q, B, R any](e IdempotentEndpoint[P, Q, B, R]) RouteID
IdempotentEndpointID returns the underlying endpoint's route identifier.
func OptionalEndpointID ¶ added in v0.2.0
func OptionalEndpointID[P, Q, B, M, R any](endpoint OptionalAuthenticationEndpoint[P, Q, B, M, R]) RouteID
OptionalEndpointID returns the endpoint's route identifier.
func SignedAuthenticatedEndpointID ¶ added in v0.2.0
func SignedAuthenticatedEndpointID[P, Q, B, S, R any](e SignedAuthenticatedEndpoint[P, Q, B, S, R]) RouteID
SignedAuthenticatedEndpointID returns the endpoint's route identifier.
func SignedEndpointID ¶ added in v0.2.0
func SignedEndpointID[P, Q, B, R any](e SignedEndpoint[P, Q, B, R]) RouteID
SignedEndpointID returns the endpoint's route identifier.
func SignedRouteID ¶ added in v0.2.0
func SignedRouteID[P any](r SignedRoute[P]) RouteID
SignedRouteID returns the underlying route identifier.
type RouteInfo ¶
type RouteInfo struct {
ID RouteID `json:"id"`
Method Method `json:"method"`
Path string `json:"path"`
Parameters []string `json:"parameters"`
Access Access `json:"access"`
Raw bool `json:"raw"`
Middlewares []MiddlewareID `json:"middlewares,omitempty"`
Assets *AssetRouteInfo `json:"assets,omitempty"`
SignedURL *SignedURLInfo `json:"signed_url,omitempty"`
Authentication *AuthenticationInfo `json:"authentication,omitempty"`
// Documentation is exported API documentation; see WithDocumentation.
Documentation *RouteDocumentation `json:"documentation,omitempty"`
// Timeout and MaxBodyBytes report a route's own replacement for the kernel
// RequestTimeout and MaxBodyBytes. Zero inherits the kernel configuration.
// They are server policy, not client contract metadata.
Timeout time.Duration `json:"-"`
MaxBodyBytes int64 `json:"-"`
// Fallback marks the router's WithFallback handler for unmatched GET/HEAD
// requests. It is inspection metadata only, like Timeout.
Fallback bool `json:"-"`
}
RouteInfo is a snapshot of registered transport metadata. Path and Parameters come from the same declaration used for runtime matching and URL generation. Raw marks a payload boundary without generated request/response guarantees.
func InspectAuthenticatedRoute ¶ added in v0.2.0
func InspectAuthenticatedRoute[P, M any](r AuthenticatedRoute[P, M]) (RouteInfo, error)
InspectAuthenticatedRoute returns validated route metadata including required authentication.
func InspectOptionalRoute ¶ added in v0.2.0
func InspectOptionalRoute[P, M any](r OptionalAuthenticationRoute[P, M]) (RouteInfo, error)
InspectOptionalRoute returns validated route metadata including optional authentication.
func InspectSignedAuthenticatedRoute ¶ added in v0.2.0
func InspectSignedAuthenticatedRoute[P, S any](r SignedAuthenticatedRoute[P, S]) (RouteInfo, error)
InspectSignedAuthenticatedRoute returns validated authentication, raw-route and signed-link metadata.
type RouteOption ¶ added in v0.2.0
type RouteOption interface {
EndpointOption
// contains filtered or unexported methods
}
RouteOption is accepted by both route and endpoint constructors.
func BodyLimit ¶ added in v0.2.0
func BodyLimit(bytes int64) RouteOption
BodyLimit declares the route's request-body byte limit.
func Documentation ¶ added in v0.2.0
func Documentation(documentation RouteDocumentation) RouteOption
Documentation snapshots route documentation for declaration metadata.
func Timeout ¶ added in v0.2.0
func Timeout(timeout time.Duration) RouteOption
Timeout declares the route's request timeout.
func Use ¶ added in v0.2.0
func Use(middleware ...Middleware) RouteOption
Use snapshots middleware to append to a route or endpoint.
func Within ¶ added in v0.2.0
func Within(scope Scope) RouteOption
Within snapshots the scope's middleware for application to a route or endpoint.
type RouteRegistration ¶
type RouteRegistration struct {
// contains filtered or unexported fields
}
RouteRegistration is the heterogeneous assembly boundary. Construct it from a Route descriptor; invalid declarations are rejected by NewRouter as a whole.
func HandleAuthenticatedBound ¶ added in v0.2.0
func HandleAuthenticatedBound[P, Q, B, M, R any](e AuthenticatedEndpoint[P, Q, B, M, R], bind AuthenticatedBinding[P, Q, B, M, R]) RouteRegistration
HandleAuthenticatedBound runs bind with the concrete actor after request (and actor) authorization and before validation; see Binding.
func HandleAuthenticatedRaw ¶ added in v0.2.0
func HandleAuthenticatedRaw[P, M any](r AuthenticatedRoute[P, M], handler func(stdhttp.ResponseWriter, *stdhttp.Request, M, P)) RouteRegistration
HandleAuthenticatedRaw admits the guard and requirements before path decoding. The original writer, URL, RequestURI, headers and body remain available to the native handler.
func HandleBound ¶ added in v0.2.0
func HandleBound[P, Q, B, R any](e Endpoint[P, Q, B, R], bind Binding[P, Q, B, R]) RouteRegistration
HandleBound runs bind after request authorization and before validation, then the handler it returned. The lifecycle is otherwise that of Handle: decode, prohibited-input check, preparation, request authorization, binding, validation, handler.
func HandleOptionalBound ¶ added in v0.2.0
func HandleOptionalBound[P, Q, B, M, R any](e OptionalAuthenticationEndpoint[P, Q, B, M, R], bind AuthenticatedBinding[P, Q, B, value.Optional[M], R]) RouteRegistration
HandleOptionalBound runs bind with the optional actor after request (and actor) authorization and before validation; see Binding.
func HandleOptionalRaw ¶ added in v0.2.0
func HandleOptionalRaw[P, M any](r OptionalAuthenticationRoute[P, M], handler func(stdhttp.ResponseWriter, *stdhttp.Request, value.Optional[M], P)) RouteRegistration
HandleOptionalRaw registers a raw HTTP handler receiving the guard's optional subject and decoded path.
func HandleRaw ¶ added in v0.2.0
func HandleRaw[P any](r Route[P], handler RawHandler[P]) RouteRegistration
HandleRaw binds a handler with the same concrete path type. Its raw payload boundary is retained in route inspection; client generators must not infer a response DTO from arbitrary writes to ResponseWriter.
func HandleSignedAuthenticatedBound ¶ added in v0.2.0
func HandleSignedAuthenticatedBound[P, Q, B, S, R any](e SignedAuthenticatedEndpoint[P, Q, B, S, R], bind AuthenticatedBinding[P, Q, B, S, R]) RouteRegistration
HandleSignedAuthenticatedBound verifies the URL like Handle, then runs the binding stage. The wrapped transport must be a framework authenticated endpoint.
func HandleSignedAuthenticatedRaw ¶ added in v0.2.0
func HandleSignedAuthenticatedRaw[P, S any](r SignedAuthenticatedRoute[P, S], handler func(stdhttp.ResponseWriter, *stdhttp.Request, S, P)) RouteRegistration
HandleSignedAuthenticatedRaw registers a typed-subject raw handler behind URL-signature verification and authentication.
func HandleSignedBound ¶ added in v0.2.0
func HandleSignedBound[P, Q, B, R any](e SignedEndpoint[P, Q, B, R], bind Binding[P, Q, B, R]) RouteRegistration
HandleSignedBound verifies the URL like Handle, then runs the binding stage.
func HandleSignedRaw ¶ added in v0.2.0
func HandleSignedRaw[P any](r SignedRoute[P], handler RawHandler[P]) RouteRegistration
HandleSignedRaw verifies before path decoding or handler execution. PublicURLs must run outside the router; TrustedProxy must precede it behind a trusted edge. Raw handlers retain the original native request and signing query parameters.
func InvalidRouteRegistration ¶
func InvalidRouteRegistration(cause error) RouteRegistration
InvalidRouteRegistration lets a typed framework adapter retain a declaration failure at the existing heterogeneous router assembly boundary. NewRouter returns this cause before publishing any handler. It does not send an HTTP error response. A nil cause still produces an invalid registration.
func PrepareAuthenticatedIdempotent ¶ added in v0.2.0
func PrepareAuthenticatedIdempotent[P, Q, B, M, R any](e AuthenticatedIdempotentEndpoint[P, Q, B, M, R], prepare func(context.Context, M, Input[P, Q, B]) (idempotency.Scope, TransactionHandler[P, Q, B, R], error)) RouteRegistration
PrepareAuthenticatedIdempotent preserves concrete authenticated identity for model-binding adapters.
func PrepareIdempotent ¶ added in v0.2.0
func PrepareIdempotent[P, Q, B, R any](e IdempotentEndpoint[P, Q, B, R], prepare TransactionPreparation[P, Q, B, R]) RouteRegistration
PrepareIdempotent is the typed composition boundary for authenticated/model-bound adapters. Policy and binding run before Run on both new requests and replays.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router is an immutable, concurrency-safe native net/http handler. All route validation completes before it is returned; startup never partially registers into a shared/global ServeMux. Registration order does not resolve ambiguity.
func NewRouter ¶
func NewRouter(registrations ...RouteRegistration) (*Router, error)
NewRouter rejects duplicate IDs, invalid bindings and ambiguous native routing patterns. It performs no I/O. The same result can be passed to HTTP Module or Prepare, or used directly by net/http testing tools.
func (*Router) Endpoints ¶
func (r *Router) Endpoints() []EndpointInfo
Endpoints returns typed metadata in route-ID order. Raw handlers remain visible through Routes and do not acquire fabricated payload schemas.
func (*Router) ErrorDefinitions ¶
func (r *Router) ErrorDefinitions() []ErrorDefinition
ErrorDefinitions returns all built-in and declared application failures in code order. Conflicting declarations are rejected when the router is built. This snapshot and EndpointInfo.Errors share the actual response declarations.
func (*Router) ServeHTTP ¶
func (r *Router) ServeHTTP(w stdhttp.ResponseWriter, request *stdhttp.Request)
ServeHTTP dispatches registered routes, rejects ambiguous encoded paths and applies framework errors and configured fallbacks to unmatched requests.
func (*Router) WithFallback ¶
WithFallback returns an independent router view whose unmatched GET and HEAD requests run handler instead of Foundry's shared not_found error, like Laravel's Route::fallback; use it for a custom 404 page. It runs only after the native router found no route and no SPA fallback served the request. Declared routes, method errors (405 with Allow) and endpoint error responses are never intercepted, and other methods keep the shared 404.
The handler owns its response, including its status (normally 404). Global middleware around the router applies to it; compose fallback-specific middleware with ApplyMiddleware. MatchedRoute, request observation and audit attribution report its ID. Route inspection lists it as the raw route GET /{path...} with RouteInfo.Fallback set. A router has at most one fallback; the original router is unchanged.
func (*Router) WithSPA ¶
WithSPA returns an independent router view sharing the immutable native route table. The fallback answers a native unmatched 404, and an asset mount with a less specific or equal prefix defers to it: a more specific SPA owns its subtree below the mount, including what it declines, and answers before the mount's middleware; an equal one answers the mount's misses inside it. Declared routes and more specific mounts keep precedence. The original router is unchanged; no endpoint error response is intercepted or rewritten.
type SPAConfig ¶
type SPAConfig struct {
Prefix string
Index AssetPath
Exclude []string
CacheControl HeaderValue
}
SPAConfig declares an unmatched-route fallback. Prefix and Exclude are absolute URL prefixes. Index is relative to Assets. Only explicit text/html navigation to extensionless missing paths falls back to Index. Existing files still serve normally. Declared API routes and native method errors take precedence.
func DefaultSPAConfig ¶
func DefaultSPAConfig() SPAConfig
DefaultSPAConfig returns a root mount with index.html and no-cache headers.
type Scope ¶
type Scope struct {
// contains filtered or unexported fields
}
Scope is an immutable literal path and route-name prefix. Access remains explicit on each route. Paths containing parameters belong in the typed Path declaration so their bindings stay attached to their concrete parameter type.
func DefineScope ¶
DefineScope creates a prefix such as /api/v1 and api.v1. Empty path/name prefixes are valid independently. A nonempty prefix has no trailing slash.
func (Scope) WithMiddleware ¶
func (s Scope) WithMiddleware(middlewares ...Middleware) Scope
WithMiddleware appends middleware inside this scope's existing chain. When nested, parent scope middleware runs before child scope and route middleware.
type SecurityHeadersConfig ¶
type SecurityHeadersConfig struct {
NoSniff bool
Frame FramePolicy
Referrer ReferrerPolicy
HSTS value.Optional[HSTSPolicy]
DisableLegacyXSSFilter bool
CrossOriginOpener CrossOriginOpenerPolicy
CrossOriginEmbedder CrossOriginEmbedderPolicy
CrossOriginResource CrossOriginResourcePolicy
Permissions []PermissionDirective
Extra []ResponseHeader
}
SecurityHeadersConfig declares response defaults before the next handler. Start with DefaultSecurityHeadersConfig. Zero emits no headers. HSTS is opt-in and applies to native TLS or a scheme validated by preceding TrustedProxy middleware. Arbitrary forwarding headers are ignored. Extra is an explicit native-header extension and does not validate arbitrary header-specific languages.
CrossOriginOpener, CrossOriginEmbedder and CrossOriginResource emit the Cross-Origin-*-Policy headers; Permissions emits a typed Permissions-Policy. All four are opt-in and omitted when zero. Extra cannot repeat a header that a typed field emits.
func DefaultSecurityHeadersConfig ¶
func DefaultSecurityHeadersConfig() SecurityHeadersConfig
DefaultSecurityHeadersConfig returns independent response defaults. HSTS is omitted until explicitly configured; no subdomains or preload are implicit.
func (SecurityHeadersConfig) Validate ¶
func (c SecurityHeadersConfig) Validate() error
Validate checks that security header policies can be compiled.
type SecurityRequestEvent ¶
type SecurityRequestEvent struct {
Request RequestEvent
ClientIP netip.Addr
Path string
PathTruncated bool
}
SecurityRequestEvent is explicitly opt-in. Path excludes the query, is bounded and has control characters removed. It remains untrusted and may contain private path values: observers must classify/redact it before retaining it. ClientIP uses the same trusted-proxy policy as admission, including early rejects.
type SecurityRequestObserver ¶
type SecurityRequestObserver interface {
RequestObserver
// ObserveSecurityRequest receives bounded security metadata for a completed request.
ObserveSecurityRequest(context.Context, SecurityRequestEvent)
}
SecurityRequestObserver extends RequestObserver without changing default payload-free observations. Both callbacks run once under request ownership.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server owns one listener and the synchronous lifetime of each admitted handler. It must not be copied or reused after Run. Use Prepare or Module; the zero value is invalid. Work launched by a raw handler after it returns, including hijacked connections, needs its own application lifecycle owner.
func Prepare ¶
func Prepare(handler stdhttp.Handler, config ServerConfig, logger *slog.Logger, options ...ServerOption) (*Server, error)
Prepare validates a standalone server without opening sockets or starting goroutines. The supplied logger is local to this server; no global is changed.
func (*Server) Done ¶
func (s *Server) Done() <-chan struct{}
Done closes after Run's listener and admitted handlers actually finish. A server that has never run is not done. A shutdown deadline cannot kill Go code.
func (*Server) Ready ¶
Ready waits for the one startup attempt and returns the actual bound TCP address. It reports binding/cancellation failure instead of inventing an address. Readiness records successful binding, not ongoing service health.
func (*Server) Run ¶
Run binds and serves once until cancellation or a listener failure. Normal cancellation stops admission, then allows active requests the configured shutdown grace. Expiry cancels their contexts and closes ordinary connections, but Run still waits for actual handler exit before releasing ownership.
type ServerConfig ¶
type ServerConfig struct {
// Address is a TCP host:port. Port zero allocates a port reported by Ready.
Address string
// ReadHeaderTimeout bounds socket time spent reading request headers.
ReadHeaderTimeout time.Duration
// ReadTimeout bounds reading the full request, including its body. It does
// not terminate handler computations or replace their context deadlines.
ReadTimeout time.Duration
// WriteTimeout bounds response socket writes, including streaming writes.
// It does not terminate a handler that ignores write errors/cancellation.
WriteTimeout time.Duration
// IdleTimeout bounds waiting for another request on a keep-alive connection.
IdleTimeout time.Duration
// RequestTimeout bounds the request context after admission. Cooperative
// handlers and database calls observe its cancellation. Ownership lasts
// until actual handler exit; raw handlers own their response behavior.
// A matched route declared with WithTimeout replaces it for that route.
RequestTimeout time.Duration
// ShutdownTimeout allows admitted handlers to finish before cancellation and
// connection closure. Dependency ownership still lasts until actual exit.
ShutdownTimeout time.Duration
// MaxHeaderBytes configures the native net/http request-header limit.
MaxHeaderBytes int
// MaxBodyBytes is a positive default ceiling for known and streamed bodies.
// Increasing it does not preallocate a buffer; raw handlers own their reads.
// A matched route declared with WithBodyLimit replaces it for that route only.
MaxBodyBytes int64
// MaxConcurrentRequests bounds handlers that have actually entered the
// server. Zero uses DefaultServerConfig's limit. A request waits briefly for
// a slot in arrival order (at most min(RequestTimeout, 5s)); exhaustion then
// returns 503 with Retry-After. Cancelled handlers retain their slot until
// they really return.
MaxConcurrentRequests int
// MaxConnections bounds accepted TCP connections, including connections
// still reading headers and hijacked connections until their owner closes
// them. Zero uses the default. Extra peers wait in the OS listen backlog.
MaxConnections int
// TrustTraceContext accepts valid W3C trace headers as correlation metadata.
// It grants no identity or sampling authority. False starts a fresh trace
// for every request; invalid or duplicate parents also start a fresh trace.
TrustTraceContext bool
// MaintenanceReadPaths permits GET/HEAD on at most 16 exact static paths
// while paused or draining. Use URLs derived from protected diagnostics
// routes. This bypasses only maintenance admission: normal route auth,
// policies, request limits and actual server shutdown still apply.
MaintenanceReadPaths []string `config:",json"`
// AccessLog emits one metadata-only completion event to the server logger.
AccessLog bool
}
ServerConfig bounds native HTTP connection I/O. Start with DefaultServerConfig and change fields explicitly. All timeouts and the header limit must be positive. MaxBodyBytes is a positive global ceiling, including streamed bodies. I/O deadlines do not terminate arbitrary handler computations.
func DefaultServerConfig ¶
func DefaultServerConfig() ServerConfig
DefaultServerConfig returns a fresh configuration for a loopback HTTP server. TLS termination, forwarded headers and public origins are separate transport concerns; no incoming proxy headers are trusted by this configuration.
func (ServerConfig) Snapshot ¶
func (c ServerConfig) Snapshot() ServerConfig
Snapshot copies caller-owned slices before a server/module retains config.
func (ServerConfig) Validate ¶
func (c ServerConfig) Validate() error
Validate checks bounds without opening a listener or resolving a hostname. Port zero requests an operating-system-assigned port, available through Ready.
type ServerOption ¶
type ServerOption func(*serverOptions) error
ServerOption configures an HTTP server during construction.
func WithAdmissionProxy ¶
func WithAdmissionProxy(proxy Middleware) ServerOption
WithAdmissionProxy lets kernel-level admission, which runs before the middleware chain, resolve the client address and scheme exactly as the given TrustedProxy middleware will: maintenance allow networks then match the client behind a trusted load balancer instead of the balancer itself, and the bypass cookie is Secure when the trusted public scheme is https. Without it admission uses the socket peer and native TLS. Configured applications pass their global TrustedProxy automatically.
func WithRequestObserver ¶
func WithRequestObserver(observer RequestObserver) ServerOption
WithRequestObserver adds a non-nil observer, rejecting more than 16 observers.
type SignedAuthenticatedEndpoint ¶
type SignedAuthenticatedEndpoint[P, Q, B, S, R any] struct { // contains filtered or unexported fields }
SignedAuthenticatedEndpoint retains the concrete subject and DTO contracts. Configure authentication requirements before Signed. Both credential admission and signature validation run before input decoding; signatures grant no identity.
func ConfigureSignedAuthenticated ¶ added in v0.2.0
func ConfigureSignedAuthenticated[P, Q, B, S, R any](endpoint SignedAuthenticatedEndpoint[P, Q, B, S, R], options ...SignedOption) SignedAuthenticatedEndpoint[P, Q, B, S, R]
ConfigureSignedAuthenticated applies signed-link options to a copy of the authenticated endpoint.
func SignedAuthenticated ¶
func SignedAuthenticated[P, Q, B, M, R any](endpoint AuthenticatedEndpoint[P, Q, B, M, R], signer URLSigner) SignedAuthenticatedEndpoint[P, Q, B, M, R]
SignedAuthenticated adds URL-signature verification while preserving the endpoint's required concrete subject.
func SignedOptionalAuthentication ¶
func SignedOptionalAuthentication[P, Q, B, M, R any](endpoint OptionalAuthenticationEndpoint[P, Q, B, M, R], signer URLSigner) SignedAuthenticatedEndpoint[P, Q, B, value.Optional[M], R]
SignedOptionalAuthentication adds URL-signature verification while preserving the endpoint's optional concrete subject.
func (SignedAuthenticatedEndpoint[P, Q, B, S, R]) Handle ¶
func (e SignedAuthenticatedEndpoint[P, Q, B, S, R]) Handle(handler func(context.Context, S, Input[P, Q, B]) (R, error)) RouteRegistration
Handle registers a typed subject callback behind URL-signature verification and the endpoint's authentication and authorization stages.
type SignedAuthenticatedRoute ¶
type SignedAuthenticatedRoute[P, S any] struct { // contains filtered or unexported fields }
SignedAuthenticatedRoute adds URL signatures without discarding the raw handler's concrete required/optional subject or its native writer capabilities.
func ConfigureSignedAuthenticatedRoute ¶ added in v0.2.0
func ConfigureSignedAuthenticatedRoute[P, S any](route SignedAuthenticatedRoute[P, S], options ...SignedOption) SignedAuthenticatedRoute[P, S]
ConfigureSignedAuthenticatedRoute applies signed-link options to a copy of the authenticated raw route.
func SignAuthenticatedRoute ¶ added in v0.2.0
func SignAuthenticatedRoute[P, M any](r AuthenticatedRoute[P, M], signer URLSigner) SignedAuthenticatedRoute[P, M]
SignAuthenticatedRoute adds URL-signature verification to a required-authentication raw route.
func SignOptionalRoute ¶ added in v0.2.0
func SignOptionalRoute[P, M any](r OptionalAuthenticationRoute[P, M], signer URLSigner) SignedAuthenticatedRoute[P, value.Optional[M]]
SignOptionalRoute adds URL-signature verification to an optional-authentication raw route.
type SignedCookie ¶
type SignedCookie[V any] struct { // contains filtered or unexported fields }
SignedCookie preserves the cookie's concrete value type while authenticating an envelope before invoking its decoder. Wire values are URL-safe encoded. MaxAge or Expires is enforced in the signed envelope. A session cookie with neither has no server-side expiry; credential lifetime belongs to authentication.
func (SignedCookie[V]) Clear ¶
func (c SignedCookie[V]) Clear(w stdhttp.ResponseWriter) error
Clear validates the signed cookie and adds its clearing Set-Cookie header.
func (SignedCookie[V]) GoString ¶
func (c SignedCookie[V]) GoString() string
GoString returns the signed cookie's name label without exposing values.
func (SignedCookie[V]) Name ¶
func (c SignedCookie[V]) Name() CookieName
Name returns the underlying cookie name.
func (SignedCookie[V]) Options ¶
func (c SignedCookie[V]) Options() CookieOptions
Options returns the underlying cookie attributes.
func (SignedCookie[V]) Read ¶
Read verifies and decodes a present cookie, returning omission when absent and BadRequest for an invalid signature.
func (SignedCookie[V]) Set ¶
func (c SignedCookie[V]) Set(ctx context.Context, w stdhttp.ResponseWriter, v V) error
Set formats and signs v and adds its Set-Cookie header after checking cancellation.
func (SignedCookie[V]) String ¶
func (c SignedCookie[V]) String() string
String returns a label containing the signed cookie's name.
func (SignedCookie[V]) Validate ¶
func (c SignedCookie[V]) Validate() error
Validate checks the cookie declaration and signer.
type SignedEndpoint ¶
type SignedEndpoint[P, Q, B, R any] struct { // contains filtered or unexported fields }
SignedEndpoint retains the original path, query, body and response types. Configure scopes, limits, validation and middleware before calling Signed. Expiry/signature are framework transport fields, never fields of a domain DTO.
func ConfigureSigned ¶ added in v0.2.0
func ConfigureSigned[P, Q, B, R any](endpoint SignedEndpoint[P, Q, B, R], options ...SignedOption) SignedEndpoint[P, Q, B, R]
ConfigureSigned applies permanent-link and ignored-parameter options to a copy of endpoint.
func Signed ¶
func Signed[P, Q, B, R any](endpoint Endpoint[P, Q, B, R], signer URLSigner) SignedEndpoint[P, Q, B, R]
Signed returns a signed endpoint preserving the original path, query, body and response types. Configure scopes, limits, validation and middleware before calling Signed. Expiry/signature are framework transport fields, never fields of a domain DTO.
func (SignedEndpoint[P, Q, B, R]) Handle ¶
func (e SignedEndpoint[P, Q, B, R]) Handle(handler Handler[P, Q, B, R]) RouteRegistration
Handle verifies the URL before any path/query/body codec, validation or domain handler. The existing endpoint decoder receives only its original typed query.
type SignedOption ¶ added in v0.2.0
type SignedOption struct {
// contains filtered or unexported fields
}
SignedOption configures permanent-link acceptance or unsigned query parameters for signed declarations.
func IgnoredParameters ¶ added in v0.2.0
func IgnoredParameters(names ...string) SignedOption
IgnoredParameters snapshots unauthenticated query parameter names to exclude from signature verification and typed query decoding.
func PermanentLinks ¶ added in v0.2.0
func PermanentLinks() SignedOption
PermanentLinks permits signed links without expiry in addition to expiring links.
type SignedRoute ¶
type SignedRoute[P any] struct { // contains filtered or unexported fields }
SignedRoute retains concrete path parameters for link generation and handlers. Apply scopes/middleware to the original route before calling Signed.
func ConfigureSignedRoute ¶ added in v0.2.0
func ConfigureSignedRoute[P any](route SignedRoute[P], options ...SignedOption) SignedRoute[P]
ConfigureSignedRoute applies permanent-link and ignored-parameter options to a copy of route.
type SignedURLInfo ¶
type SignedURLInfo struct {
Version string `json:"version"`
Algorithm string `json:"algorithm"`
ExpiresParameter string `json:"expires_parameter"`
SignatureParameter string `json:"signature_parameter"`
Relative bool `json:"relative"`
Permanent bool `json:"permanent,omitempty"`
IgnoredParameters []string `json:"ignored_parameters,omitempty"`
}
SignedURLInfo describes framework-owned query parameters separately from an endpoint's domain query, and the route's link policy, so clients accept the links the route verifies. Relative links (RelativeURL) are accepted on every admitted origin; Permanent links carry no expiry parameter; IgnoredParameters are unauthenticated extras (for example analytics tags) removed before verification. Inspection/export never exposes signing key material.
func (SignedURLInfo) Validate ¶
func (info SignedURLInfo) Validate() error
Validate checks serialized inspection metadata against the runtime signer. It exposes no keys and does not generate or verify a credential.
type SigningKey ¶
type SigningKey struct {
ID SigningKeyID
Secret secret.String
}
SigningKey pairs a public identifier with explicitly protected key material. Use cryptographically random material. Length validation cannot prove entropy.
func (SigningKey) GoString ¶
func (k SigningKey) GoString() string
GoString returns the redaction marker without exposing the key.
func (SigningKey) String ¶
func (k SigningKey) String() string
String returns the redaction marker without exposing the key.
type SigningKeyID ¶
type SigningKeyID string
SigningKeyID is the public rotation identifier, not secret key material.
type SigningKeys ¶
type SigningKeys struct {
// contains filtered or unexported fields
}
SigningKeys is an immutable rotation set. Active signs new values; previous keys only verify. Removing a key invalidates signatures created with that key.
func NewSigningKeys ¶
func NewSigningKeys(active SigningKey, previous ...SigningKey) (SigningKeys, error)
NewSigningKeys copies at most sixteen distinct keys. IDs are bounded ASCII letters, digits, underscores or hyphens. Material is 32–1024 bytes. Neither keys nor their signatures are inferred from an application name or environment.
func (SigningKeys) ActiveID ¶
func (k SigningKeys) ActiveID() SigningKeyID
ActiveID returns the identifier used for new signatures.
func (SigningKeys) GoString ¶
func (k SigningKeys) GoString() string
GoString returns the redaction marker without exposing keys.
func (SigningKeys) String ¶
func (k SigningKeys) String() string
String returns the redaction marker without exposing keys.
func (SigningKeys) Validate ¶
func (k SigningKeys) Validate() error
Validate requires the selected active key to exist in the key set.
type Statused ¶
Statused is a typed JSON result together with the success status its handler selected from the response descriptor's declared statuses (see JSONResponses). A zero Status selects the primary status.
type Stream ¶
type Stream struct {
// contains filtered or unexported fields
}
Stream is a deferred finite response that requires no Seek implementation. It has no range or cache-validator contract; use Download for those features. Copies share the source callback but open independently for each request.
func StreamFrom ¶
func StreamFrom(source StreamSource) Stream
StreamFrom binds a streaming source with default file presentation.
func (Stream) MarshalJSON ¶
MarshalJSON rejects JSON serialization because a stream requires a file response contract.
func (Stream) Progressive ¶
Progressive flushes each chunk to the client as soon as the source produced and Foundry accepted it, for incremental output such as a long export or a log tail. Without it the native writer may buffer small chunks. Length and byte-limit checks are unchanged: a flushed prefix can still be aborted by a later failure, never completed early. Declare the route's WithTimeout for streams that outlive the kernel RequestTimeout.
func (Stream) WithDisposition ¶
func (s Stream) WithDisposition(disposition Disposition) Stream
WithDisposition returns a stream with the selected disposition.
func (Stream) WithMediaType ¶
WithMediaType returns a stream with an explicitly supplied media type.
type StreamContent ¶
type StreamContent struct {
Body io.ReadCloser
Name string
MediaType MediaType
Length value.Optional[int64]
}
StreamContent is one finite, unseekable representation. Length is optional: unset means unknown, Set(0) means empty. A supplied length must match EOF. Ownership of Body transfers when StreamSource returns, even alongside an error. Reads must terminate or honor the source context. Foundry never abandons a callback or closes its body concurrently with a read.
type StreamSource ¶
type StreamSource func(context.Context) (StreamContent, error)
StreamSource opens a representation only after its endpoint handler succeeds. HEAD opens metadata and closes Body without reading. Before returning, the source owns every resource it creates, including its own producer goroutines.
type TicketEndpoint ¶ added in v0.4.0
type TicketEndpoint[P, Q, B, M, R any] struct { // contains filtered or unexported fields }
TicketEndpoint authenticates a guarded GET using only a single-use ticket. Its concrete actor and request lifecycle are those of AuthenticatedEndpoint.
func TicketAuthenticated ¶ added in v0.4.0
func TicketAuthenticated[P, Q, B, M, R any](endpoint Endpoint[P, Q, B, R], binding GuardBinding[M], redeemer auth.TicketRedeemer, options ...GuardOption[M]) TicketEndpoint[P, Q, B, M, R]
TicketAuthenticated binds a GET endpoint to ticket-only authentication. The query must not declare ticket; the transport consumes it before typed decoding. Guard options retain their ordinary scopes, permissions and actor middleware.
func (TicketEndpoint[P, Q, B, M, R]) Handle ¶ added in v0.4.0
func (e TicketEndpoint[P, Q, B, M, R]) Handle(handler func(context.Context, M, Input[P, Q, B]) (R, error)) RouteRegistration
Handle registers a callback with the current concrete actor. The authentication scope remains open through response streaming. HEAD never redeems a ticket.
func (TicketEndpoint[P, Q, B, M, R]) URL ¶ added in v0.4.0
func (e TicketEndpoint[P, Q, B, M, R]) URL(ctx context.Context, path P, query Q, ticket secret.String) (string, error)
URL explicitly delivers a single-use ticket in a typed, relative route URL. Treat the result as a credential: use HTTPS and redact it from logs/history. A retry or resumed download requires a fresh ticket.
type TransactionHandler ¶
type TransactionHandler[P, Q, B, R any] func(context.Context, *database.Tx, Input[P, Q, B]) (R, error)
TransactionHandler retains the concrete wire input/result and requires the runner-owned transaction. It cannot receive or write an HTTP response writer.
type TransactionPreparation ¶
type TransactionPreparation[P, Q, B, R any] func(context.Context, Input[P, Q, B]) (idempotency.Scope, TransactionHandler[P, Q, B, R], error)
TransactionPreparation runs on EVERY request, before claiming or replaying. Resolve current resource policy and trusted scope here. The returned closure may capture that request's concrete authorized models for the winning callback.
type TrustedProxyConfig ¶
type TrustedProxyConfig struct {
Proxies []netip.Prefix
// Headers select client-IP forwarding sources.
Headers []ProxyHeader
// OriginHeaders select public scheme/authority sources independently.
OriginHeaders []ProxyOriginHeader
}
TrustedProxyConfig owns explicit peer networks and ordered header sources. Zero trusts no peers. Networks do not automatically include loopback, private networks or a CDN. A nonempty network list requires explicit IP or origin header sources. A trusted peer must append trustworthy chain entries or overwrite single-IP headers; CIDR membership alone cannot prove its forwarding configuration.
func (TrustedProxyConfig) Validate ¶
func (c TrustedProxyConfig) Validate() error
Validate checks that trusted proxy networks and header declarations can be compiled.
type URLScalarInfo ¶
URLScalarInfo describes the decoded scalar value and the URL codec used by the runtime. Custom syntax retains server-owned parsing rules; its declared value shape does not imply an equivalent browser implementation.
func DescribePathCodec ¶
func DescribePathCodec[V any](codec PathCodec[V]) (URLScalarInfo, error)
DescribePathCodec exposes the same scalar metadata used by path/query/cookie declarations for other typed text boundaries. Custom codecs use DescribeURL.
func (URLScalarInfo) Normalize ¶
func (info URLScalarInfo) Normalize() (URLScalarInfo, error)
Normalize validates and owns a serialized scalar description. It promises only the declared URL syntax; CustomURLSyntax still needs its native codec or an explicitly supplied equivalent client codec.
type URLSigner ¶
type URLSigner struct {
// contains filtered or unexported fields
}
URLSigner binds temporary links to their route ID, method, pattern, public origin and exact escaped path/query. It shares SigningKeys with cookies but uses a distinct HMAC purpose. Links are replayable until expiry; body content, authentication, one-time consumption and encryption remain separate concerns.
func NewURLSigner ¶
func NewURLSigner(keys SigningKeys, applicationClock clock.Clock) (URLSigner, error)
NewURLSigner validates and binds signing keys and the application clock.
type URLSyntax ¶
type URLSyntax string
URLSyntax describes the scalar codec's lexical contract before URL escaping. Cardinality and path structure remain in the parameter's own descriptor.
const ( TextURLSyntax URLSyntax = "text" IntegerURLSyntax URLSyntax = "integer" FloatURLSyntax URLSyntax = "float" BooleanURLSyntax URLSyntax = "boolean" ModelIDURLSyntax URLSyntax = "model_id" EnumURLSyntax URLSyntax = "enum" FormattedURLSyntax URLSyntax = "formatted" CustomURLSyntax URLSyntax = "custom" )
type UploadedFile ¶
UploadedFile is a fully captured, request-owned file. Open supplies a bounded lifetime native reader; Name, Size and content-type methods expose metadata. Temporary paths stay private. Files cannot be implicitly serialized as JSON or retained for a job after the request ends; persist them through storage.
Source Files
¶
- assets.go
- assets_config.go
- assets_metadata.go
- assets_module.go
- assets_route.go
- assets_source.go
- authenticated_actor.go
- authenticated_endpoint.go
- authenticated_lifecycle.go
- authenticated_route.go
- authenticated_transport.go
- authentication.go
- authentication_binding.go
- authentication_capture.go
- authentication_retry.go
- binding_transport.go
- body_operations.go
- body_raw.go
- browser_session_confirmation.go
- browser_session_impersonation.go
- browser_session_state.go
- browser_sessions.go
- cache_headers.go
- compression.go
- compression_brotli.go
- compression_capabilities.go
- compression_config.go
- compression_head.go
- compression_negotiation.go
- compression_policy.go
- compression_response.go
- content_disposition.go
- contribution_contract.go
- contributions.go
- cookie.go
- cookie_codec.go
- cookie_encrypted.go
- cookie_encrypter.go
- cookie_options.go
- cookie_response.go
- cookie_signer.go
- cors.go
- cors_config.go
- credential_metadata.go
- credential_requests.go
- credential_response.go
- csp.go
- csp_policy.go
- csp_source.go
- csrf.go
- download.go
- download_local.go
- download_open_unix.go
- download_response.go
- endpoint.go
- endpoint_body.go
- endpoint_cleanup.go
- endpoint_error.go
- endpoint_lifecycle.go
- endpoint_limits.go
- endpoint_metadata.go
- endpoint_payload.go
- endpoint_response.go
- endpoint_transport.go
- endpoint_validation.go
- error_classification.go
- error_contract.go
- error_declaration.go
- error_messages.go
- errors.go
- etag.go
- etag_conditions.go
- etag_config.go
- etag_policy.go
- etag_response.go
- file_metadata.go
- file_presentation.go
- file_reader.go
- file_response_headers.go
- file_response_limits.go
- file_response_metadata.go
- file_response_runtime.go
- file_response_source.go
- file_response_writer.go
- form_body.go
- forwarded.go
- guard_binding.go
- handler_lifetime.go
- header_name.go
- header_value.go
- idempotency.go
- idempotency_authentication.go
- idempotency_encoding.go
- idempotency_metadata.go
- idempotency_middleware.go
- locale.go
- maintenance_access.go
- mfa_request.go
- mfa_response.go
- middleware.go
- module.go
- multipart.go
- multipart_body.go
- multipart_limits.go
- multipart_part.go
- observed_response.go
- options.go
- origin.go
- origin_pattern.go
- path.go
- path_codec.go
- path_float.go
- path_metadata.go
- path_parameter.go
- path_text_codec.go
- presentation.go
- proxy_addresses.go
- proxy_config.go
- proxy_origin.go
- public_url.go
- query.go
- query_codec.go
- query_composition.go
- query_consumed.go
- query_default.go
- query_parameter.go
- rate_limit.go
- refresh_cookie.go
- request_context.go
- request_logger.go
- request_metrics.go
- request_observation.go
- request_observer.go
- request_security.go
- response_buffer.go
- response_capabilities.go
- response_headers.go
- response_metadata.go
- response_redirect.go
- response_status.go
- route.go
- route_budget.go
- route_documentation.go
- route_error.go
- route_fallback.go
- route_middleware.go
- route_scope.go
- router.go
- security_headers.go
- security_headers_config.go
- security_headers_policies.go
- security_policies.go
- server.go
- server_config.go
- signed_authenticated_endpoint.go
- signed_authenticated_route.go
- signed_cookie.go
- signed_endpoint.go
- signed_route.go
- signing_clock.go
- signing_keys.go
- spa.go
- spa_config.go
- statement_detector.go
- stream.go
- stream_events.go
- stream_events_response.go
- stream_response.go
- stream_response_runtime.go
- table_operation.go
- ticket_endpoint.go
- ticket_response.go
- token_request.go
- token_response.go
- transport_metadata.go
- trusted_proxy.go
- uploaded_file.go
- url_scalar.go
- url_scalar_metadata.go
- url_signer.go
- url_type.go
- webhook.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package modelbinding resolves typed route keys into concrete models before domain handlers run.
|
Package modelbinding resolves typed route keys into concrete models before domain handlers run. |
|
Package pagination adapts typed database pages to HTTP request and response contracts.
|
Package pagination adapts typed database pages to HTTP request and response contracts. |