Error messages related to schema validation and returned as results.
const ( // ArrayDoesNotAllowAdditionalItemsError when an additionalItems construct is not verified by the array values provided. // // TODO: should move to package go-openapi/errors ArrayDoesNotAllowAdditionalItemsError = "array doesn't allow for additional items" // HasDependencyError indicates that a dependencies construct was not verified HasDependencyError = "%q has a dependency on %s" // InvalidSchemaProvidedError indicates that the schema provided to validate a value cannot be properly compiled InvalidSchemaProvidedError = "Invalid schema provided to SchemaValidator: %v" // InvalidTypeConversionError indicates that a numerical conversion for the given type could not be carried on InvalidTypeConversionError = "invalid type conversion in %s: %v " // MustValidateAtLeastOneSchemaError indicates that in a AnyOf construct, none of the schema constraints specified were verified MustValidateAtLeastOneSchemaError = "%q must validate at least one schema (anyOf)" // MustValidateOnlyOneSchemaError indicates that in a OneOf construct, either none of the schema constraints specified were verified, or several were MustValidateOnlyOneSchemaError = "%q must validate one and only one schema (oneOf). %s" // MustValidateAllSchemasError indicates that in a AllOf construct, at least one of the schema constraints specified were not verified // // TODO: punctuation in message MustValidateAllSchemasError = "%q must validate all the schemas (allOf)%s" // MustNotValidateSchemaError indicates that in a Not construct, the schema constraint specified was verified MustNotValidateSchemaError = "%q must not validate the schema (not)" )
Error messages related to spec validation and returned as results.
const ( // ArrayRequiresItemsError ... ArrayRequiresItemsError = "%s for %q is a collection without an element type (array requires items definition)" // ArrayInParamRequiresItemsError ... ArrayInParamRequiresItemsError = "param %q for %q is a collection without an element type (array requires item definition)" // ArrayInHeaderRequiresItemsError ... ArrayInHeaderRequiresItemsError = "header %q for %q is a collection without an element type (array requires items definition)" // BothFormDataAndBodyError indicates that an operation specifies both a body and a formData parameter, which is forbidden BothFormDataAndBodyError = "operation %q has both formData and body parameters. Only one such In: type may be used for a given operation" // CannotResolveRefError when a $ref could not be resolved CannotResolveReferenceError = "could not resolve reference in %s to $ref %s: %v" // CircularAncestryDefinitionError ... CircularAncestryDefinitionError = "definition %q has circular ancestry: %v" // DefaultValueDoesNotValidateError results from an invalid default value provided DefaultValueDoesNotValidateError = "default value for %s in %s does not validate its schema" // DefaultValueItemsDoesNotValidateError results from an invalid default value provided for Items DefaultValueItemsDoesNotValidateError = "default value for %s.items in %s does not validate its schema" // DefaultValueHeaderDoesNotValidateError results from an invalid default value provided in header DefaultValueHeaderDoesNotValidateError = "in operation %q, default value in header %s for %s does not validate its schema" // DefaultValueHeaderItemsDoesNotValidateError results from an invalid default value provided in header.items DefaultValueHeaderItemsDoesNotValidateError = "in operation %q, default value in header.items %s for %s does not validate its schema" // DefaultValueInDoesNotValidateError ... DefaultValueInDoesNotValidateError = "in operation %q, default value in %s does not validate its schema" // DuplicateParamNameError ... DuplicateParamNameError = "duplicate parameter name %q for %q in operation %q" // DuplicatePropertiesError ... DuplicatePropertiesError = "definition %q contains duplicate properties: %v" // ExampleValueDoesNotValidateError results from an invalid example value provided ExampleValueDoesNotValidateError = "example value for %s in %s does not validate its schema" // ExampleValueItemsDoesNotValidateError results from an invalid example value provided for Items ExampleValueItemsDoesNotValidateError = "example value for %s.items in %s does not validate its schema" // ExampleValueHeaderDoesNotValidateError results from an invalid example value provided in header ExampleValueHeaderDoesNotValidateError = "in operation %q, example value in header %s for %s does not validate its schema" // ExampleValueHeaderItemsDoesNotValidateError results from an invalid example value provided in header.items ExampleValueHeaderItemsDoesNotValidateError = "in operation %q, example value in header.items %s for %s does not validate its schema" // ExampleValueInDoesNotValidateError ... ExampleValueInDoesNotValidateError = "in operation %q, example value in %s does not validate its schema" // EmptyPathParameterError means that a path parameter was found empty (e.g. "{}") EmptyPathParameterError = "%q contains an empty path parameter" // InvalidDocumentError states that spec validation only processes spec.Document objects InvalidDocumentError = "spec validator can only validate spec.Document objects" // InvalidItemsPatternError indicates an Items definition with invalid pattern InvalidItemsPatternError = "%s for %q has invalid items pattern: %q" // InvalidParameterDefinitionError indicates an error detected on a parameter definition InvalidParameterDefinitionError = "invalid definition for parameter %s in %s in operation %q" // InvalidParameterDefinitionAsSchemaError indicates an error detected on a parameter definition, which was mistaken with a schema definition. // Most likely, this situation is encountered whenever a $ref has been added as a sibling of the parameter definition. InvalidParameterDefinitionAsSchemaError = "invalid definition as Schema for parameter %s in %s in operation %q" // InvalidPatternError ... InvalidPatternError = "pattern %q is invalid in %s" // InvalidPatternInError indicates an invalid pattern in a schema or items definition InvalidPatternInError = "%s in %s has invalid pattern: %q" // InvalidPatternInHeaderError indicates a header definition with an invalid pattern InvalidPatternInHeaderError = "in operation %q, header %s for %s has invalid pattern %q: %v" // InvalidPatternInParamError ... InvalidPatternInParamError = "operation %q has invalid pattern in param %q: %q" // InvalidReferenceError indicates that a $ref property could not be resolved InvalidReferenceError = "invalid ref %q" // InvalidResponseDefinitionAsSchemaError indicates an error detected on a response definition, which was mistaken with a schema definition. // Most likely, this situation is encountered whenever a $ref has been added as a sibling of the response definition. InvalidResponseDefinitionAsSchemaError = "invalid definition as Schema for response %s in %s" // MultipleBodyParamError indicates that an operation specifies multiple parameter with in: body MultipleBodyParamError = "operation %q has more than 1 body param: %v" // NonUniqueOperationIDError indicates that the same operationId has been specified several times NonUniqueOperationIDError = "%q is defined %d times" // NoParameterInPathError indicates that a path was found without any parameter NoParameterInPathError = "path param %q has no parameter definition" // NoValidPathErrorOrWarning indicates that no single path could be validated. If Paths is empty, this message is only a warning. NoValidPathErrorOrWarning = "spec has no valid path defined" // NoValidResponseError indicates that no valid response description could be found for an operation NoValidResponseError = "operation %q has no valid response" // PathOverlapError ... PathOverlapError = "path %s overlaps with %s" // PathParamNotInPathError indicates that a parameter specified with in: path was not found in the path specification PathParamNotInPathError = "path param %q is not present in path %q" // PathParamNotUniqueError ... PathParamNotUniqueError = "params in path %q must be unique: %q conflicts with %q" // PathParamNotRequiredError ... PathParamRequiredError = "in operation %q,path param %q must be declared as required" // RefNotAllowedInHeaderError indicates a $ref was found in a header definition, which is not allowed by Swagger RefNotAllowedInHeaderError = "IMPORTANT!in %q: $ref are not allowed in headers. In context for header %q%s" // RequiredButNotDefinedError ... RequiredButNotDefinedError = "%q is present in required but not defined as property in definition %q" // SomeParametersBrokenError indicates that some parameters could not be resolved, which might result in partial checks to be carried on SomeParametersBrokenError = "some parameters definitions are broken in %q.%s. Cannot carry on full checks on parameters for operation %s" // UnresolvedReferencesError indicates that at least one $ref could not be resolved UnresolvedReferencesError = "some references could not be resolved in spec. First found: %v" )
Warning messages related to spec validation and returned as results
const ( // ExamplesWithoutSchemaWarning indicates that examples are provided for a response,but not schema to validate the example against ExamplesWithoutSchemaWarning = "Examples provided without schema in operation %q, %s" // ExamplesMimeNotSupportedWarning indicates that examples are provided with a mime type different than application/json, which // the validator dos not support yetl ExamplesMimeNotSupportedWarning = "No validation attempt for examples for media types other than application/json, in operation %q, %s" // PathParamGarbledWarning ... PathParamGarbledWarning = "in path %q, param %q contains {,} or white space. Albeit not stricly illegal, this is probably no what you want" // ParamValidationTypeMismatch indicates that parameter has validation which does not match its type ParamValidationTypeMismatch = "validation keywords of parameter %q in path %q don't match its type %s" // PathStrippedParamGarbledWarning ... PathStrippedParamGarbledWarning = "path stripped from path parameters %s contains {,} or white space. This is probably no what you want." // ReadOnlyAndRequiredWarning ... ReadOnlyAndRequiredWarning = "Required property %s in %q should not be marked as both required and readOnly" // RefShouldNotHaveSiblingsWarning indicates that a $ref was found with a sibling definition. This results in the $ref taking over its siblings, // which is most likely not wanted. RefShouldNotHaveSiblingsWarning = "$ref property should have no sibling in %q.%s" // RequiredHasDefaultWarning indicates that a required parameter property should not have a default RequiredHasDefaultWarning = "%s in %s has a default value and is required as parameter" // UnusedDefinitionWarning ... UnusedDefinitionWarning = "definition %q is not used anywhere" // UnusedParamWarning ... UnusedParamWarning = "parameter %q is not used anywhere" // UnusedResponseWarning ... UnusedResponseWarning = "response %q is not used anywhere" InvalidObject = "expected an object in %q.%s" )
Additional error codes
const ( // InternalErrorCode reports an internal technical error InternalErrorCode = http.StatusInternalServerError // NotFoundErrorCode indicates that a resource (e.g. a $ref) could not be found NotFoundErrorCode = http.StatusNotFound )
var ( // Debug is true when the SWAGGER_DEBUG env var is not empty. // It enables a more verbose logging of validators. Debug = os.Getenv("SWAGGER_DEBUG") != "" )
func AgainstSchema(schema *spec.Schema, data interface{}, formats strfmt.Registry, options ...Option) error
AgainstSchema validates the specified data against the provided schema, using a registry of supported formats.
When no pre-parsed *spec.Schema structure is provided, it uses a JSON schema as default. See example.
▹ Example
func Enum(path, in string, data interface{}, enum interface{}) *errors.Validation
Enum validates if the data is a member of the enum
func EnumCase(path, in string, data interface{}, enum interface{}, caseSensitive bool) *errors.Validation
EnumCase validates if the data is a member of the enum and may respect case-sensitivity for strings
func FormatOf(path, in, format, data string, registry strfmt.Registry) *errors.Validation
FormatOf validates if a string matches a format in the format registry
func IsValueValidAgainstRange(val interface{}, typeName, format, prefix, path string) error
IsValueValidAgainstRange checks that a numeric value is compatible with the range defined by Type and Format, that is, may be converted without loss.
NOTE: this check is about type capacity and not formal verification such as: 1.0 != 1L
func MaxItems(path, in string, size, max int64) *errors.Validation
MaxItems validates that there are at most n items in a slice
func MaxLength(path, in, data string, maxLength int64) *errors.Validation
MaxLength validates a string for maximum length
func Maximum(path, in string, data, max float64, exclusive bool) *errors.Validation
Maximum validates if a number is smaller than a given maximum
func MaximumInt(path, in string, data, max int64, exclusive bool) *errors.Validation
MaximumInt validates if a number is smaller than a given maximum
func MaximumNativeType(path, in string, val interface{}, max float64, exclusive bool) *errors.Validation
MaximumNativeType provides native type constraint validation as a facade to various numeric types versions of Maximum constraint check.
Assumes that any possible loss conversion during conversion has been checked beforehand.
NOTE: currently, the max value is marshalled as a float64, no matter what, which means there may be a loss during conversions (e.g. for very large integers)
TODO: Normally, a JSON MAX_SAFE_INTEGER check would ensure conversion remains loss-free
func MaximumUint(path, in string, data, max uint64, exclusive bool) *errors.Validation
MaximumUint validates if a number is smaller than a given maximum
func MinItems(path, in string, size, min int64) *errors.Validation
MinItems validates that there are at least n items in a slice
func MinLength(path, in, data string, minLength int64) *errors.Validation
MinLength validates a string for minimum length
func Minimum(path, in string, data, min float64, exclusive bool) *errors.Validation
Minimum validates if a number is smaller than a given minimum
func MinimumInt(path, in string, data, min int64, exclusive bool) *errors.Validation
MinimumInt validates if a number is smaller than a given minimum
func MinimumNativeType(path, in string, val interface{}, min float64, exclusive bool) *errors.Validation
MinimumNativeType provides native type constraint validation as a facade to various numeric types versions of Minimum constraint check.
Assumes that any possible loss conversion during conversion has been checked beforehand.
NOTE: currently, the min value is marshalled as a float64, no matter what, which means there may be a loss during conversions (e.g. for very large integers)
TODO: Normally, a JSON MAX_SAFE_INTEGER check would ensure conversion remains loss-free
func MinimumUint(path, in string, data, min uint64, exclusive bool) *errors.Validation
MinimumUint validates if a number is smaller than a given minimum
func MultipleOf(path, in string, data, factor float64) *errors.Validation
MultipleOf validates if the provided number is a multiple of the factor
func MultipleOfInt(path, in string, data int64, factor int64) *errors.Validation
MultipleOfInt validates if the provided integer is a multiple of the factor
func MultipleOfNativeType(path, in string, val interface{}, multipleOf float64) *errors.Validation
MultipleOfNativeType provides native type constraint validation as a facade to various numeric types version of MultipleOf constraint check.
Assumes that any possible loss conversion during conversion has been checked beforehand.
NOTE: currently, the multipleOf factor is marshalled as a float64, no matter what, which means there may be a loss during conversions (e.g. for very large integers)
TODO: Normally, a JSON MAX_SAFE_INTEGER check would ensure conversion remains loss-free
func MultipleOfUint(path, in string, data, factor uint64) *errors.Validation
MultipleOfUint validates if the provided unsigned integer is a multiple of the factor
func Pattern(path, in, data, pattern string) *errors.Validation
Pattern validates a string against a regular expression
func ReadOnly(ctx context.Context, path, in string, data interface{}) *errors.Validation
ReadOnly validates an interface for readonly
func Required(path, in string, data interface{}) *errors.Validation
Required validates an interface for requiredness
func RequiredNumber(path, in string, data float64) *errors.Validation
RequiredNumber validates a number for requiredness
func RequiredString(path, in, data string) *errors.Validation
RequiredString validates a string for requiredness
func SetContinueOnErrors(c bool)
SetContinueOnErrors sets global default behavior regarding spec validation errors reporting.
For extended error reporting, you most likely want to set it to true. For faster validation, it's better to give up early when a spec is detected as invalid: set it to false (this is the default).
Setting this mode does NOT affect the validation status.
NOTE: this method affects global defaults. It is not suitable for a concurrent usage.
func Spec(doc *loads.Document, formats strfmt.Registry) error
Spec validates an OpenAPI 2.0 specification document.
Returns an error flattening in a single standard error, all validation messages.
NOTE: SecurityScopes are maps: no need to check uniqueness
▹ Example
▹ Example (Second)
func UniqueItems(path, in string, data interface{}) *errors.Validation
UniqueItems validates that the provided slice has unique elements
func WithOperationRequest(ctx context.Context) context.Context
WithOperationRequest returns a new context with operationType request in context value
func WithOperationResponse(ctx context.Context) context.Context
WithOperationRequest returns a new context with operationType response in context value
An EntityValidator is an interface for things that can validate entities
type EntityValidator interface { Validate(interface{}) *Result }
FieldKey is a pair of an object and a field, usable as a key for a map.
type FieldKey struct {
// contains filtered or unexported fields
}
func NewFieldKey(obj map[string]interface{}, field string) FieldKey
NewFieldKey returns a pair of an object and field usable as a key of a map.
func (fk *FieldKey) Field() string
Field returns the underlying field of this key.
func (fk *FieldKey) Object() map[string]interface{}
Object returns the underlying object of this key.
A HeaderValidator has very limited subset of validations to apply
type HeaderValidator struct { KnownFormats strfmt.Registry Options *SchemaValidatorOptions // contains filtered or unexported fields }
func NewHeaderValidator(name string, header *spec.Header, formats strfmt.Registry, options ...Option) *HeaderValidator
NewHeaderValidator creates a new header validator object
func (p *HeaderValidator) Validate(data interface{}) *Result
Validate the value of the header against its schema
ItemKey is a pair of a slice and an index, usable as a key for a map.
type ItemKey struct {
// contains filtered or unexported fields
}
func NewItemKey(slice interface{}, i int) ItemKey
NewItemKey returns a pair of a slice and index usable as a key of a map.
func (ik *ItemKey) Index() int
Index returns the underlying index of this key.
func (ik *ItemKey) Slice() []interface{}
Slice returns the underlying slice of this key.
Option sets optional rules for schema validation
type Option func(*SchemaValidatorOptions)
func EnableArrayMustHaveItemsCheck(enable bool) Option
EnableArrayMustHaveItemsCheck activates the swagger rule: an array must have items defined
func EnableObjectArrayTypeCheck(enable bool) Option
EnableObjectArrayTypeCheck activates the swagger rule: an items must be in type: array
func SwaggerSchema(enable bool) Option
SwaggerSchema activates swagger schema validation rules
func WithRecycleValidators(enable bool) Option
WithRecycleValidators saves memory allocations and makes validators available for a single use of Validate() only.
When a validator is recycled, called MUST not call the Validate() method twice.
func WithSkipSchemataResult(enable bool) Option
WithSkipSchemataResult skips the deep audit payload stored in validation Result
Opts specifies validation options for a SpecValidator.
NOTE: other options might be needed, for example a go-swagger specific mode.
type Opts struct { ContinueOnErrors bool // true: continue reporting errors, even if spec is invalid // StrictPathParamUniqueness enables a strict validation of paths that include // path parameters. When true, it will enforce that for each method, the path // is unique, regardless of path parameters such that GET:/petstore/{id} and // GET:/petstore/{pet} anre considered duplicate paths. // // Consider disabling if path parameters can include slashes such as // GET:/v1/{shelve} and GET:/v1/{book}, where the IDs are "shelve/*" and // /"shelve/*/book/*" respectively. StrictPathParamUniqueness bool SkipSchemataResult bool }
A ParamValidator has very limited subset of validations to apply
type ParamValidator struct { KnownFormats strfmt.Registry Options *SchemaValidatorOptions // contains filtered or unexported fields }
func NewParamValidator(param *spec.Parameter, formats strfmt.Registry, options ...Option) *ParamValidator
NewParamValidator creates a new param validator object
func (p *ParamValidator) Validate(data interface{}) *Result
Validate the data against the description of the parameter
Result represents a validation result set, composed of errors and warnings.
It is used to keep track of all detected errors and warnings during the validation of a specification.
Matchcount is used to determine which errors are relevant in the case of AnyOf, OneOf schema validation. Results from the validation branch with most matches get eventually selected.
TODO: keep path of key originating the error
type Result struct { Errors []error Warnings []error MatchCount int // contains filtered or unexported fields }
func (r *Result) AddErrors(errors ...error)
AddErrors adds errors to this validation result (if not already reported).
Since the same check may be passed several times while exploring the spec structure (via $ref, ...) reported messages are kept unique.
func (r *Result) AddWarnings(warnings ...error)
AddWarnings adds warnings to this validation result (if not already reported).
func (r *Result) AsError() error
AsError renders this result as an error interface
TODO: reporting / pretty print with path ordered and indented
func (r *Result) Data() interface{}
Data returns the original data object used for validation. Mutating this renders the result invalid.
func (r *Result) FieldSchemata() map[FieldKey][]*spec.Schema
FieldSchemata returns the schemata which apply to fields in objects.
func (r *Result) HasErrors() bool
HasErrors returns true when this result is invalid.
Returns false on a nil *Result.
func (r *Result) HasErrorsOrWarnings() bool
HasErrorsOrWarnings returns true when this result contains either errors or warnings.
Returns false on a nil *Result.
func (r *Result) HasWarnings() bool
HasWarnings returns true when this result contains warnings.
Returns false on a nil *Result.
func (r *Result) Inc()
Inc increments the match count
func (r *Result) IsValid() bool
IsValid returns true when this result is valid.
Returns true on a nil *Result.
func (r *Result) ItemSchemata() map[ItemKey][]*spec.Schema
ItemSchemata returns the schemata which apply to items in slices.
func (r *Result) Merge(others ...*Result) *Result
Merge merges this result with the other one(s), preserving match counts etc.
func (r *Result) MergeAsErrors(others ...*Result) *Result
MergeAsErrors merges this result with the other one(s), preserving match counts etc.
Warnings from input are merged as Errors in the returned merged Result.
func (r *Result) MergeAsWarnings(others ...*Result) *Result
MergeAsWarnings merges this result with the other one(s), preserving match counts etc.
Errors from input are merged as Warnings in the returned merged Result.
func (r *Result) RootObjectSchemata() []*spec.Schema
RootObjectSchemata returns the schemata which apply to the root object.
SchemaValidator validates data against a JSON schema
type SchemaValidator struct { Path string Schema *spec.Schema Root interface{} KnownFormats strfmt.Registry Options *SchemaValidatorOptions // contains filtered or unexported fields }
func NewSchemaValidator(schema *spec.Schema, rootSchema interface{}, root string, formats strfmt.Registry, options ...Option) *SchemaValidator
NewSchemaValidator creates a new schema validator.
Panics if the provided schema is invalid.
func (s *SchemaValidator) Applies(source interface{}, _ reflect.Kind) bool
Applies returns true when this schema validator applies
func (s *SchemaValidator) SetPath(path string)
SetPath sets the path for this schema valdiator
func (s *SchemaValidator) Validate(data interface{}) *Result
Validate validates the data against the schema
SchemaValidatorOptions defines optional rules for schema validation
type SchemaValidatorOptions struct { EnableObjectArrayTypeCheck bool EnableArrayMustHaveItemsCheck bool // contains filtered or unexported fields }
func (svo SchemaValidatorOptions) Options() []Option
Options returns the current set of options
SpecValidator validates a swagger 2.0 spec
type SpecValidator struct { KnownFormats strfmt.Registry Options Opts // validation options // contains filtered or unexported fields }
func NewSpecValidator(schema *spec.Schema, formats strfmt.Registry) *SpecValidator
NewSpecValidator creates a new swagger spec validator instance
func (s *SpecValidator) SetContinueOnErrors(c bool)
SetContinueOnErrors sets the ContinueOnErrors option for this validator.
func (s *SpecValidator) Validate(data interface{}) (*Result, *Result)
Validate validates the swagger spec
▹ Example
▹ Example (Url)