Documentation
¶
Index ¶
- type AuthenticationFunc
- type AuthenticationInput
- type ContentParameterDecoder
- type ContentParameterInput
- type Option
- func DisablePathTree() Option
- func WithAuthenticationFunc(fn AuthenticationFunc) Option
- func WithBodyDecoder(mediaType string, decoder content.Decoder) Option
- func WithBodyEncoder(mediaType string, encoder content.Encoder) Option
- func WithContentAssertions() Option
- func WithContentParameterDecoder(decoder ContentParameterDecoder) Option
- func WithContentParameterValidation() Option
- func WithCustomFormat(name string, validator func(v any) error) Option
- func WithExistingOpts(options *ValidationOptions) Option
- func WithFormatAssertions() Option
- func WithLogger(logger *slog.Logger) Option
- func WithOpenAPIMode() Option
- func WithPathTree(pathTree radix.PathLookup) Option
- func WithRegexCache(regexCache RegexCache) Option
- func WithRegexEngine(engine jsonschema.RegexpEngine) Option
- func WithRejectUndeclaredRequestBody() Option
- func WithRejectUnsupportedBodyContent() Option
- func WithRequestDefaults() Option
- func WithScalarCoercion() Option
- func WithSchemaCache(schemaCache cache.SchemaCache) Option
- func WithSchemaResourceCache(schemaResourceCache cache.SchemaResourceCache) Option
- func WithStandardBodyDecoders() Option
- func WithStrictIgnorePaths(paths ...string) Option
- func WithStrictIgnoredHeaders(headers ...string) Option
- func WithStrictIgnoredHeadersExtra(headers ...string) Option
- func WithStrictMode() Option
- func WithStrictRejectReadOnly() Option
- func WithStrictRejectWriteOnly() Option
- func WithStrictServerMatching() Option
- func WithURLEncodedBodyValidation() Option
- func WithXmlBodyValidation() Option
- func WithZipBodyDecoder(limits content.ZipLimits) Option
- func WithoutOpenAPIMode() Option
- func WithoutRequestBodyValidation() Option
- func WithoutRequestQueryParameterValidation() Option
- func WithoutResponseBodyValidation() Option
- func WithoutResponseStatusValidation() Option
- func WithoutSecurityValidation() Option
- type RegexCache
- type ValidationOptions
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AuthenticationFunc ¶ added in v0.13.7
type AuthenticationFunc func(context.Context, *AuthenticationInput) error
AuthenticationFunc validates one security scheme for an HTTP request. Return nil when the scheme is satisfied; return an error to fail the current security requirement. Each invocation receives a fresh replayable body reader.
type AuthenticationInput ¶ added in v0.13.7
type AuthenticationInput struct {
Request *http.Request // Request is the request being authenticated.
SecuritySchemeName string // SecuritySchemeName is the component key from the requirement.
SecurityScheme *v3.SecurityScheme // SecurityScheme is the resolved OpenAPI scheme.
Scopes []string // Scopes contains the scopes required by this requirement.
Path string // Path is the matched OpenAPI path template.
PathItem *v3.PathItem // PathItem is the matched OpenAPI path item.
Operation *v3.Operation // Operation is the matched OpenAPI operation.
PathParams map[string]string // PathParams contains decoded operation path parameters.
Server *v3.Server // Server is the effective matched server, if explicit.
ServerParams map[string]string // ServerParams contains decoded server variables.
}
AuthenticationInput contains the request and OpenAPI security scheme details passed to an AuthenticationFunc.
type ContentParameterDecoder ¶ added in v0.14.0
type ContentParameterDecoder func(context.Context, *ContentParameterInput) (value any, schema *base.Schema, err error)
ContentParameterDecoder decodes an OpenAPI Parameter.content value and may select a schema.
type ContentParameterInput ¶ added in v0.14.0
type ContentParameterInput struct {
Parameter *v3.Parameter // Parameter is the OpenAPI parameter being decoded.
RawValues []string // RawValues contains all query values or the single non-query value.
MediaType string // MediaType is the declared Parameter.content media type.
DefaultSchema *base.Schema // DefaultSchema is the schema declared by the selected media type.
Request *http.Request // Request is the request being validated.
PathParams map[string]string // PathParams contains decoded operation path parameters.
ServerVariables map[string]string // ServerVariables contains decoded server variables.
}
ContentParameterInput contains raw parameter values and matched route context.
type Option ¶
type Option func(*ValidationOptions)
Option Enables an 'Options pattern' approach
func DisablePathTree ¶ added in v0.13.0
func DisablePathTree() Option
DisablePathTree prevents automatic radix tree construction. Use this to fall back to regex-based path matching only.
func WithAuthenticationFunc ¶ added in v0.13.7
func WithAuthenticationFunc(fn AuthenticationFunc) Option
WithAuthenticationFunc sets a custom function for validating security requirements. When set, the function is authoritative for all security scheme types, including oauth2 and openIdConnect.
func WithBodyDecoder ¶ added in v0.14.0
WithBodyDecoder registers a per-validator body decoder. Later exact registrations win.
func WithBodyEncoder ¶ added in v0.14.0
WithBodyEncoder registers a per-validator body encoder. Later exact registrations win.
func WithContentAssertions ¶ added in v0.4.0
func WithContentAssertions() Option
WithContentAssertions enables checks for contentType, contentEncoding, etc
func WithContentParameterDecoder ¶ added in v0.14.0
func WithContentParameterDecoder(decoder ContentParameterDecoder) Option
WithContentParameterDecoder enables Parameter.content validation with a custom per-validator decoder.
func WithContentParameterValidation ¶ added in v0.14.0
func WithContentParameterValidation() Option
WithContentParameterValidation enables built-in JSON Parameter.content validation for path, header, and cookie parameters. Existing query Parameter.content behavior remains enabled independently for compatibility.
func WithCustomFormat ¶ added in v0.5.0
WithCustomFormat adds custom formats and their validators that checks for custom 'format' assertions When you add different validators with the same name, they will be overridden, and only the last registration will take effect.
func WithExistingOpts ¶ added in v0.4.4
func WithExistingOpts(options *ValidationOptions) Option
WithExistingOpts returns an Option that will copy the values from the supplied ValidationOptions instance
func WithFormatAssertions ¶ added in v0.4.0
func WithFormatAssertions() Option
WithFormatAssertions enables checks for 'format' assertions (such as date, date-time, uuid, etc)
func WithLogger ¶ added in v0.10.0
WithLogger sets the logger for validation debug/error output. If not set, logging is silent (nil logger is handled gracefully).
func WithOpenAPIMode ¶ added in v0.6.0
func WithOpenAPIMode() Option
WithOpenAPIMode enables OpenAPI-specific keyword validation (default: true)
func WithPathTree ¶ added in v0.13.0
func WithPathTree(pathTree radix.PathLookup) Option
WithPathTree sets a custom radix tree for path matching. The default is built automatically from the OpenAPI specification.
func WithRegexCache ¶ added in v0.9.0
func WithRegexCache(regexCache RegexCache) Option
WithRegexCache assigns a cache for compiled regular expressions. A sync.Map should be sufficient for most use cases. It does not implement any cleanup
func WithRegexEngine ¶
func WithRegexEngine(engine jsonschema.RegexpEngine) Option
WithRegexEngine Assigns a custom regular-expression engine to be used during validation.
func WithRejectUndeclaredRequestBody ¶ added in v0.14.0
func WithRejectUndeclaredRequestBody() Option
WithRejectUndeclaredRequestBody rejects non-empty bodies on operations without requestBody.
func WithRejectUnsupportedBodyContent ¶ added in v0.14.0
func WithRejectUnsupportedBodyContent() Option
WithRejectUnsupportedBodyContent rejects declared body media types without a decoder.
func WithRequestDefaults ¶ added in v0.14.0
func WithRequestDefaults() Option
WithRequestDefaults stages query, header, cookie, and request-body defaults and commits them atomically after successful decoding, encoding, and validation.
func WithScalarCoercion ¶ added in v0.6.0
func WithScalarCoercion() Option
WithScalarCoercion enables string to boolean/number coercion (Jackson-style)
func WithSchemaCache ¶ added in v0.8.0
func WithSchemaCache(schemaCache cache.SchemaCache) Option
WithSchemaCache sets a custom cache implementation or disables caching if nil. Pass nil to disable schema caching and skip cache warming during validator initialization. The default cache is a thread-safe sync.Map wrapper.
func WithSchemaResourceCache ¶ added in v0.13.13
func WithSchemaResourceCache(schemaResourceCache cache.SchemaResourceCache) Option
WithSchemaResourceCache sets a cache for rendered document-level schema resources. Pass nil to disable resource reuse when compiling referenced schemas. Cached entries retain source YAML nodes, so long-lived shared caches should be bounded or scoped deliberately.
func WithStandardBodyDecoders ¶ added in v0.14.0
func WithStandardBodyDecoders() Option
WithStandardBodyDecoders enables YAML, generic XML, URL-encoded forms, multipart forms, plain text, CSV, and binary codecs. ZIP remains separately opt-in through WithZipBodyDecoder.
func WithStrictIgnorePaths ¶ added in v0.10.0
WithStrictIgnorePaths sets JSONPath patterns for paths to exclude from strict validation. Patterns use glob syntax:
- * matches a single path segment
- ** matches any depth (zero or more segments)
- [*] matches any array index
- \* escapes a literal asterisk
Examples:
- "$.body.metadata.*" - any property under metadata
- "$.body.**.x-*" - any x-* property at any depth
- "$.headers.X-*" - any header starting with X-
func WithStrictIgnoredHeaders ¶ added in v0.10.0
WithStrictIgnoredHeaders replaces the default ignored headers list entirely. Use this to fully control which headers are ignored in strict mode. For the default list, see the strict package's DefaultIgnoredHeaders.
func WithStrictIgnoredHeadersExtra ¶ added in v0.10.0
WithStrictIgnoredHeadersExtra adds headers to the default ignored list. Unlike WithStrictIgnoredHeaders, this merges with the defaults rather than replacing them.
func WithStrictMode ¶ added in v0.10.0
func WithStrictMode() Option
WithStrictMode enables strict property validation. In strict mode, undeclared properties are reported as errors even when additionalProperties: true would normally allow them.
This is useful for API governance scenarios where you want to ensure clients only send properties that are explicitly documented in the OpenAPI specification.
func WithStrictRejectReadOnly ¶ added in v0.13.4
func WithStrictRejectReadOnly() Option
WithStrictRejectReadOnly enables rejection of readOnly properties in requests. When enabled, readOnly properties present in request bodies are reported as validation errors instead of being silently skipped.
func WithStrictRejectWriteOnly ¶ added in v0.13.4
func WithStrictRejectWriteOnly() Option
WithStrictRejectWriteOnly enables rejection of writeOnly properties in responses. When enabled, writeOnly properties present in response bodies are reported as validation errors instead of being silently skipped.
func WithStrictServerMatching ¶ added in v0.14.0
func WithStrictServerMatching() Option
WithStrictServerMatching enables standalone-router server semantics in high-level validation.
func WithURLEncodedBodyValidation ¶ added in v0.12.0
func WithURLEncodedBodyValidation() Option
WithURLEncodedBodyValidation enables converting an URL Encoded body to a JSON when validating the schema from a request and response body The default option is set to false
func WithXmlBodyValidation ¶ added in v0.12.0
func WithXmlBodyValidation() Option
WithXmlBodyValidation enables converting an XML body to a JSON when validating the schema from a request and response body The default option is set to false
func WithZipBodyDecoder ¶ added in v0.14.0
WithZipBodyDecoder enables ZIP validation bounded by limits.
func WithoutOpenAPIMode ¶ added in v0.6.0
func WithoutOpenAPIMode() Option
WithoutOpenAPIMode disables OpenAPI-specific keyword validation
func WithoutRequestBodyValidation ¶ added in v0.14.0
func WithoutRequestBodyValidation() Option
WithoutRequestBodyValidation excludes all request-body policy, defaults, decoding, and validation.
func WithoutRequestQueryParameterValidation ¶ added in v0.14.0
func WithoutRequestQueryParameterValidation() Option
WithoutRequestQueryParameterValidation excludes query validation from high-level request validation.
func WithoutResponseBodyValidation ¶ added in v0.14.0
func WithoutResponseBodyValidation() Option
WithoutResponseBodyValidation excludes response content and schema checks while retaining status and headers.
func WithoutResponseStatusValidation ¶ added in v0.14.0
func WithoutResponseStatusValidation() Option
WithoutResponseStatusValidation allows undocumented response status codes.
func WithoutSecurityValidation ¶ added in v0.5.0
func WithoutSecurityValidation() Option
WithoutSecurityValidation disables security validation for request validation
type RegexCache ¶ added in v0.9.0
type RegexCache interface {
Load(key any) (value any, ok bool) // Get a compiled regex from the cache
Store(key, value any) // Set a compiled regex to the cache
}
RegexCache can be set to enable compiled regex caching. It can be just a sync.Map, or a custom implementation with possible cleanup.
Be aware that the cache should be thread safe
type ValidationOptions ¶
type ValidationOptions struct {
RegexEngine jsonschema.RegexpEngine
RegexCache RegexCache // Enable compiled regex caching
FormatAssertions bool
ContentAssertions bool
SecurityValidation bool
AuthenticationFunc AuthenticationFunc
// ContentParameterDecoder replaces built-in Parameter.content decoding when non-nil.
ContentParameterDecoder ContentParameterDecoder
// ValidateContentParameters enables built-in JSON decoding for path, header, and cookie Parameter.content values.
// Existing query Parameter.content behavior remains enabled independently.
ValidateContentParameters bool
OpenAPIMode bool // Enable OpenAPI-specific vocabulary validation
AllowScalarCoercion bool // Enable string->boolean/number coercion
Formats map[string]func(v any) error
SchemaCache cache.SchemaCache // Optional cache for compiled schemas
SchemaResourceCache cache.SchemaResourceCache // Optional cache for rendered document-level schema resources
PathTree radix.PathLookup // O(k) path lookup via radix tree (built automatically)
Router router.Router // Shared immutable request router, when constructed by the high-level validator.
Logger *slog.Logger // Logger for debug/error output (nil = silent)
AllowXMLBodyValidation bool // Allows to convert XML to JSON for validating a request/response body.
AllowURLEncodedBodyValidation bool // Allows to convert URL Encoded to JSON for validating a request/response body.
BodyRegistry *content.Registry // BodyRegistry is the frozen per-validator body codec registry.
RejectUnsupportedBodyContent bool // RejectUnsupportedBodyContent rejects declared media types without a decoder.
RejectUndeclaredRequestBody bool // RejectUndeclaredRequestBody rejects bodies on operations without requestBody.
ValidateRequestQuery bool // ValidateRequestQuery controls high-level query validation.
ValidateRequestBody bool // ValidateRequestBody controls high-level request-body validation.
ValidateResponseBody bool // ValidateResponseBody controls high-level response-body validation.
ValidateResponseStatus bool // ValidateResponseStatus rejects undocumented response status codes.
RequestDefaults bool // RequestDefaults stages and atomically applies request defaults.
StrictServerMatching bool // StrictServerMatching matches scheme, host, port, base path, and server variables.
// strict mode options - detect undeclared properties even when additionalProperties: true
StrictMode bool // Enable strict property validation
StrictIgnorePaths []string // Instance JSONPath patterns to exclude from strict checks
StrictIgnoredHeaders []string // Headers to always ignore in strict mode (nil = use defaults)
StrictRejectReadOnly bool // Reject readOnly properties in requests
StrictRejectWriteOnly bool // Reject writeOnly properties in responses
// contains filtered or unexported fields
}
ValidationOptions A container for validation configuration.
Generally fluent With... style functions are used to establish the desired behavior.
func NewValidationOptions ¶
func NewValidationOptions(opts ...Option) *ValidationOptions
NewValidationOptions creates a new ValidationOptions instance with default values.
func (*ValidationOptions) GetEffectiveStrictIgnoredHeaders ¶ added in v0.10.0
func (o *ValidationOptions) GetEffectiveStrictIgnoredHeaders() []string
GetEffectiveStrictIgnoredHeaders returns the list of headers to ignore based on configuration. Returns defaults if not configured, merged list if extra headers were added, or replaced list if headers were fully replaced.
func (*ValidationOptions) IsPathTreeDisabled ¶ added in v0.13.0
func (o *ValidationOptions) IsPathTreeDisabled() bool
IsPathTreeDisabled returns true if radix tree auto-build was disabled via DisablePathTree.
func (*ValidationOptions) Release ¶ added in v0.13.13
func (o *ValidationOptions) Release()
Release clears cached validation state and drops references that can keep parsed documents, rendered schemas, path trees, or user-provided callbacks alive.