...

Package validate

import "github.com/go-openapi/validate"
Overview
Index
Examples
Subdirectories

Overview ▾

Package validate provides methods to validate a swagger specification, as well as tools to validate data against their schema.

This package follows Swagger 2.0. specification (aka OpenAPI 2.0). Reference can be found here: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md.

Validating a specification

Validates a spec document (from JSON or YAML) against the JSON schema for swagger, then checks a number of extra rules that can't be expressed in JSON schema.

Entry points:

  • Spec()
  • NewSpecValidator()
  • SpecValidator.Validate()

Reported as errors:

[x] definition can't declare a property that's already defined by one of its ancestors
[x] definition's ancestor can't be a descendant of the same model
[x] path uniqueness: each api path should be non-verbatim (account for path param names) unique per method. Validation can be laxed by disabling StrictPathParamUniqueness.
[x] each security reference should contain only unique scopes
[x] each security scope in a security definition should be unique
[x] parameters in path must be unique
[x] each path parameter must correspond to a parameter placeholder and vice versa
[x] each referenceable definition must have references
[x] each definition property listed in the required array must be defined in the properties of the model
[x] each parameter should have a unique `name` and `type` combination
[x] each operation should have only 1 parameter of type body
[x] each reference must point to a valid object
[x] every default value that is specified must validate against the schema for that property
[x] items property is required for all schemas/definitions of type `array`
[x] path parameters must be declared a required
[x] headers must not contain $ref
[x] schema and property examples provided must validate against their respective object's schema
[x] examples provided must validate their schema

Reported as warnings:

[x] path parameters should not contain any of [{,},\w]
[x] empty path
[x] unused definitions
[x] unsupported validation of examples on non-JSON media types
[x] examples in response without schema
[x] readOnly properties should not be required

Validating a schema

The schema validation toolkit validates data against JSON-schema-draft 04 schema.

It is tested against the full json-schema-testing-suite (https://github.com/json-schema-org/JSON-Schema-Test-Suite), except for the optional part (bignum, ECMA regexp, ...).

It supports the complete JSON-schema vocabulary, including keywords not supported by Swagger (e.g. additionalItems, ...)

Entry points:

  • AgainstSchema()
  • ...

Known limitations

With the current version of this package, the following aspects of swagger are not yet supported:

[ ] errors and warnings are not reported with key/line number in spec
[ ] default values and examples on responses only support application/json producer type
[ ] invalid numeric constraints (such as Minimum, etc..) are not checked except for default and example values
[ ] rules for collectionFormat are not implemented
[ ] no validation rule for polymorphism support (discriminator) [not done here]
[ ] valid js ECMA regexp not supported by Go regexp engine are considered invalid
[ ] arbitrary large numbers are not supported: max is math.MaxFloat64

Index ▾

Constants
Variables
func AgainstSchema(schema *spec.Schema, data interface{}, formats strfmt.Registry, options ...Option) error
func Enum(path, in string, data interface{}, enum interface{}) *errors.Validation
func EnumCase(path, in string, data interface{}, enum interface{}, caseSensitive bool) *errors.Validation
func FormatOf(path, in, format, data string, registry strfmt.Registry) *errors.Validation
func IsValueValidAgainstRange(val interface{}, typeName, format, prefix, path string) error
func MaxItems(path, in string, size, max int64) *errors.Validation
func MaxLength(path, in, data string, maxLength int64) *errors.Validation
func Maximum(path, in string, data, max float64, exclusive bool) *errors.Validation
func MaximumInt(path, in string, data, max int64, exclusive bool) *errors.Validation
func MaximumNativeType(path, in string, val interface{}, max float64, exclusive bool) *errors.Validation
func MaximumUint(path, in string, data, max uint64, exclusive bool) *errors.Validation
func MinItems(path, in string, size, min int64) *errors.Validation
func MinLength(path, in, data string, minLength int64) *errors.Validation
func Minimum(path, in string, data, min float64, exclusive bool) *errors.Validation
func MinimumInt(path, in string, data, min int64, exclusive bool) *errors.Validation
func MinimumNativeType(path, in string, val interface{}, min float64, exclusive bool) *errors.Validation
func MinimumUint(path, in string, data, min uint64, exclusive bool) *errors.Validation
func MultipleOf(path, in string, data, factor float64) *errors.Validation
func MultipleOfInt(path, in string, data int64, factor int64) *errors.Validation
func MultipleOfNativeType(path, in string, val interface{}, multipleOf float64) *errors.Validation
func MultipleOfUint(path, in string, data, factor uint64) *errors.Validation
func Pattern(path, in, data, pattern string) *errors.Validation
func ReadOnly(ctx context.Context, path, in string, data interface{}) *errors.Validation
func Required(path, in string, data interface{}) *errors.Validation
func RequiredNumber(path, in string, data float64) *errors.Validation
func RequiredString(path, in, data string) *errors.Validation
func SetContinueOnErrors(c bool)
func Spec(doc *loads.Document, formats strfmt.Registry) error
func UniqueItems(path, in string, data interface{}) *errors.Validation
func WithOperationRequest(ctx context.Context) context.Context
func WithOperationResponse(ctx context.Context) context.Context
type EntityValidator
type FieldKey
    func NewFieldKey(obj map[string]interface{}, field string) FieldKey
    func (fk *FieldKey) Field() string
    func (fk *FieldKey) Object() map[string]interface{}
type HeaderValidator
    func NewHeaderValidator(name string, header *spec.Header, formats strfmt.Registry, options ...Option) *HeaderValidator
    func (p *HeaderValidator) Validate(data interface{}) *Result
type ItemKey
    func NewItemKey(slice interface{}, i int) ItemKey
    func (ik *ItemKey) Index() int
    func (ik *ItemKey) Slice() []interface{}
type Option
    func EnableArrayMustHaveItemsCheck(enable bool) Option
    func EnableObjectArrayTypeCheck(enable bool) Option
    func SwaggerSchema(enable bool) Option
    func WithRecycleValidators(enable bool) Option
    func WithSkipSchemataResult(enable bool) Option
type Opts
type ParamValidator
    func NewParamValidator(param *spec.Parameter, formats strfmt.Registry, options ...Option) *ParamValidator
    func (p *ParamValidator) Validate(data interface{}) *Result
type Result
    func (r *Result) AddErrors(errors ...error)
    func (r *Result) AddWarnings(warnings ...error)
    func (r *Result) AsError() error
    func (r *Result) Data() interface{}
    func (r *Result) FieldSchemata() map[FieldKey][]*spec.Schema
    func (r *Result) HasErrors() bool
    func (r *Result) HasErrorsOrWarnings() bool
    func (r *Result) HasWarnings() bool
    func (r *Result) Inc()
    func (r *Result) IsValid() bool
    func (r *Result) ItemSchemata() map[ItemKey][]*spec.Schema
    func (r *Result) Merge(others ...*Result) *Result
    func (r *Result) MergeAsErrors(others ...*Result) *Result
    func (r *Result) MergeAsWarnings(others ...*Result) *Result
    func (r *Result) RootObjectSchemata() []*spec.Schema
type SchemaValidator
    func NewSchemaValidator(schema *spec.Schema, rootSchema interface{}, root string, formats strfmt.Registry, options ...Option) *SchemaValidator
    func (s *SchemaValidator) Applies(source interface{}, _ reflect.Kind) bool
    func (s *SchemaValidator) SetPath(path string)
    func (s *SchemaValidator) Validate(data interface{}) *Result
type SchemaValidatorOptions
    func (svo SchemaValidatorOptions) Options() []Option
type SpecValidator
    func NewSpecValidator(schema *spec.Schema, formats strfmt.Registry) *SpecValidator
    func (s *SpecValidator) SetContinueOnErrors(c bool)
    func (s *SpecValidator) Validate(data interface{}) (*Result, *Result)

Package files

context.go debug.go default_validator.go doc.go example_validator.go formats.go helpers.go object_validator.go options.go pools.go result.go rexp.go schema.go schema_messages.go schema_option.go schema_props.go slice_validator.go spec.go spec_messages.go type.go validator.go values.go

Constants

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
)

Variables

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

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

Code:

// Example using encoding/json as unmarshaller
var schemaJSON = `
{
    "properties": {
        "name": {
            "type": "string",
            "pattern": "^[A-Za-z]+$",
            "minLength": 1
        }
    },
    "patternProperties": {
      "address-[0-9]+": {
         "type": "string",
         "pattern": "^[\\s|a-z]+$"
      }
    },
    "required": [
        "name"
    ],
    "additionalProperties": false
}`

schema := new(spec.Schema)
_ = json.Unmarshal([]byte(schemaJSON), schema)

input := map[string]interface{}{}

// JSON data to validate
inputJSON := `{"name": "Ivan","address-1": "sesame street"}`
_ = json.Unmarshal([]byte(inputJSON), &input)

// strfmt.Default is the registry of recognized formats
err := validate.AgainstSchema(schema, input, strfmt.Default)
if err != nil {
    fmt.Printf("JSON does not validate against schema: %v", err)
} else {
    fmt.Printf("OK")
}

Output:

OK

func Enum

func Enum(path, in string, data interface{}, enum interface{}) *errors.Validation

Enum validates if the data is a member of the enum

func EnumCase

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

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

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

func MaxItems(path, in string, size, max int64) *errors.Validation

MaxItems validates that there are at most n items in a slice

func MaxLength

func MaxLength(path, in, data string, maxLength int64) *errors.Validation

MaxLength validates a string for maximum length

func Maximum

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

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

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

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

func MinItems(path, in string, size, min int64) *errors.Validation

MinItems validates that there are at least n items in a slice

func MinLength

func MinLength(path, in, data string, minLength int64) *errors.Validation

MinLength validates a string for minimum length

func Minimum

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

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

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

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

func MultipleOf(path, in string, data, factor float64) *errors.Validation

MultipleOf validates if the provided number is a multiple of the factor

func MultipleOfInt

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

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

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

func Pattern(path, in, data, pattern string) *errors.Validation

Pattern validates a string against a regular expression

func ReadOnly

func ReadOnly(ctx context.Context, path, in string, data interface{}) *errors.Validation

ReadOnly validates an interface for readonly

func Required

func Required(path, in string, data interface{}) *errors.Validation

Required validates an interface for requiredness

func RequiredNumber

func RequiredNumber(path, in string, data float64) *errors.Validation

RequiredNumber validates a number for requiredness

func RequiredString

func RequiredString(path, in, data string) *errors.Validation

RequiredString validates a string for requiredness

func SetContinueOnErrors

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

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

Code:

// Example with high level spec validation call, without showing warnings

// Example with spec file in this repo:
path := "fixtures/validation/valid-ref.json"
doc, err := loads.Spec(path)
if err == nil {
    validate.SetContinueOnErrors(true)         // Set global options
    errs := validate.Spec(doc, strfmt.Default) // Validates spec with default Swagger 2.0 format definitions

    if errs == nil {
        fmt.Println("This spec is valid")
    } else {
        fmt.Printf("This spec has some validation errors: %v\n", errs)
    }
} else {
    fmt.Println("Could not load this spec")
}

Output:

This spec is valid

Example (Second)

Code:

// Example with high level spec validation call, without showing warnings

// Example with online spec URL:
url := "http://petstore.swagger.io/v2/swagger.json"
doc, err := loads.JSONSpec(url)
if err == nil {
    validate.SetContinueOnErrors(true)         // Set global options
    errs := validate.Spec(doc, strfmt.Default) // Validates spec with default Swagger 2.0 format definitions

    if errs == nil {
        fmt.Println("This spec is valid")
    } else {
        fmt.Printf("This spec has some validation errors: %v\n", errs)
    }
} else {
    fmt.Println("Could not load this spec:", err)
}

Output:

This spec is valid

func UniqueItems

func UniqueItems(path, in string, data interface{}) *errors.Validation

UniqueItems validates that the provided slice has unique elements

func WithOperationRequest

func WithOperationRequest(ctx context.Context) context.Context

WithOperationRequest returns a new context with operationType request in context value

func WithOperationResponse

func WithOperationResponse(ctx context.Context) context.Context

WithOperationRequest returns a new context with operationType response in context value

type EntityValidator

An EntityValidator is an interface for things that can validate entities

type EntityValidator interface {
    Validate(interface{}) *Result
}

type FieldKey

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

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 (*FieldKey) Field

func (fk *FieldKey) Field() string

Field returns the underlying field of this key.

func (*FieldKey) Object

func (fk *FieldKey) Object() map[string]interface{}

Object returns the underlying object of this key.

type HeaderValidator

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

func NewHeaderValidator(name string, header *spec.Header, formats strfmt.Registry, options ...Option) *HeaderValidator

NewHeaderValidator creates a new header validator object

func (*HeaderValidator) Validate

func (p *HeaderValidator) Validate(data interface{}) *Result

Validate the value of the header against its schema

type ItemKey

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

func NewItemKey(slice interface{}, i int) ItemKey

NewItemKey returns a pair of a slice and index usable as a key of a map.

func (*ItemKey) Index

func (ik *ItemKey) Index() int

Index returns the underlying index of this key.

func (*ItemKey) Slice

func (ik *ItemKey) Slice() []interface{}

Slice returns the underlying slice of this key.

type Option

Option sets optional rules for schema validation

type Option func(*SchemaValidatorOptions)

func EnableArrayMustHaveItemsCheck

func EnableArrayMustHaveItemsCheck(enable bool) Option

EnableArrayMustHaveItemsCheck activates the swagger rule: an array must have items defined

func EnableObjectArrayTypeCheck

func EnableObjectArrayTypeCheck(enable bool) Option

EnableObjectArrayTypeCheck activates the swagger rule: an items must be in type: array

func SwaggerSchema

func SwaggerSchema(enable bool) Option

SwaggerSchema activates swagger schema validation rules

func WithRecycleValidators

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

func WithSkipSchemataResult(enable bool) Option

WithSkipSchemataResult skips the deep audit payload stored in validation Result

type Opts

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
}

type ParamValidator

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

func NewParamValidator(param *spec.Parameter, formats strfmt.Registry, options ...Option) *ParamValidator

NewParamValidator creates a new param validator object

func (*ParamValidator) Validate

func (p *ParamValidator) Validate(data interface{}) *Result

Validate the data against the description of the parameter

type Result

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 (*Result) AddErrors

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 (*Result) AddWarnings

func (r *Result) AddWarnings(warnings ...error)

AddWarnings adds warnings to this validation result (if not already reported).

func (*Result) AsError

func (r *Result) AsError() error

AsError renders this result as an error interface

TODO: reporting / pretty print with path ordered and indented

func (*Result) Data

func (r *Result) Data() interface{}

Data returns the original data object used for validation. Mutating this renders the result invalid.

func (*Result) FieldSchemata

func (r *Result) FieldSchemata() map[FieldKey][]*spec.Schema

FieldSchemata returns the schemata which apply to fields in objects.

func (*Result) HasErrors

func (r *Result) HasErrors() bool

HasErrors returns true when this result is invalid.

Returns false on a nil *Result.

func (*Result) HasErrorsOrWarnings

func (r *Result) HasErrorsOrWarnings() bool

HasErrorsOrWarnings returns true when this result contains either errors or warnings.

Returns false on a nil *Result.

func (*Result) HasWarnings

func (r *Result) HasWarnings() bool

HasWarnings returns true when this result contains warnings.

Returns false on a nil *Result.

func (*Result) Inc

func (r *Result) Inc()

Inc increments the match count

func (*Result) IsValid

func (r *Result) IsValid() bool

IsValid returns true when this result is valid.

Returns true on a nil *Result.

func (*Result) ItemSchemata

func (r *Result) ItemSchemata() map[ItemKey][]*spec.Schema

ItemSchemata returns the schemata which apply to items in slices.

func (*Result) Merge

func (r *Result) Merge(others ...*Result) *Result

Merge merges this result with the other one(s), preserving match counts etc.

func (*Result) MergeAsErrors

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 (*Result) MergeAsWarnings

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 (*Result) RootObjectSchemata

func (r *Result) RootObjectSchemata() []*spec.Schema

RootObjectSchemata returns the schemata which apply to the root object.

type SchemaValidator

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

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 (*SchemaValidator) Applies

func (s *SchemaValidator) Applies(source interface{}, _ reflect.Kind) bool

Applies returns true when this schema validator applies

func (*SchemaValidator) SetPath

func (s *SchemaValidator) SetPath(path string)

SetPath sets the path for this schema valdiator

func (*SchemaValidator) Validate

func (s *SchemaValidator) Validate(data interface{}) *Result

Validate validates the data against the schema

type SchemaValidatorOptions

SchemaValidatorOptions defines optional rules for schema validation

type SchemaValidatorOptions struct {
    EnableObjectArrayTypeCheck    bool
    EnableArrayMustHaveItemsCheck bool
    // contains filtered or unexported fields
}

func (SchemaValidatorOptions) Options

func (svo SchemaValidatorOptions) Options() []Option

Options returns the current set of options

type SpecValidator

SpecValidator validates a swagger 2.0 spec

type SpecValidator struct {
    KnownFormats strfmt.Registry
    Options      Opts // validation options
    // contains filtered or unexported fields
}

func NewSpecValidator

func NewSpecValidator(schema *spec.Schema, formats strfmt.Registry) *SpecValidator

NewSpecValidator creates a new swagger spec validator instance

func (*SpecValidator) SetContinueOnErrors

func (s *SpecValidator) SetContinueOnErrors(c bool)

SetContinueOnErrors sets the ContinueOnErrors option for this validator.

func (*SpecValidator) Validate

func (s *SpecValidator) Validate(data interface{}) (*Result, *Result)

Validate validates the swagger spec

Example

Code:

// Example of spec validation call with full result

// Example with online spec URL:
// url := "http://petstore.swagger.io/v2/swagger.json"
// doc, err := loads.JSONSpec(url)

// Example with spec file in this repo:
path := "fixtures/validation/valid-ref.json"
doc, err := loads.Spec(path)
if err == nil {
    validator := validate.NewSpecValidator(doc.Schema(), strfmt.Default)
    validator.SetContinueOnErrors(true)  // Set option for this validator
    result, _ := validator.Validate(doc) // Validates spec with default Swagger 2.0 format definitions
    if result.IsValid() {
        fmt.Println("This spec is valid")
    } else {
        fmt.Println("This spec has some validation errors")
    }
    if result.HasWarnings() {
        fmt.Println("This spec has some validation warnings")
    }
}

Output:

This spec is valid
This spec has some validation warnings

Example (Url)

Code:

// Example of spec validation call with full result

// Example with online spec URL:
url := "http://petstore.swagger.io/v2/swagger.json"
doc, err := loads.JSONSpec(url)
if err == nil {
    validator := validate.NewSpecValidator(doc.Schema(), strfmt.Default)
    validator.SetContinueOnErrors(true)  // Set option for this validator
    result, _ := validator.Validate(doc) // Validates spec with default Swagger 2.0 format definitions
    if result.IsValid() {
        fmt.Println("This spec is valid")
    } else {
        fmt.Println("This spec has some validation errors")
    }
    if result.HasWarnings() {
        fmt.Println("This spec has some validation warnings")
    }
}

Output:

This spec is valid

Subdirectories

Name Synopsis
..
post