Documentation
¶
Index ¶
- Variables
- func AddError(perr *error, err error, loc string)
- func AddValidationErrorStruct(perr *error, ve *ValidationError)
- func ClearVocabularies()
- func EnsureInstanceLocation(err error, ptr string) error
- func IsValidationError(err error) bool
- func NewValidateError(err error, errs []*ValidationError) error
- func RegisterVocabulary(v *Vocabulary, def bool)
- func SetDefaultSchema(s string) error
- func SetLoader(fn func(schemaID string, uri *url.URL) (*Schema, error)) func(string, *url.URL) (*Schema, error)
- type ArgType
- type ArrayOrSchema
- type Keyword
- type Part
- type PartAny
- type PartBool
- type PartFloat
- type PartInt
- type PartMapArrayOrSchema
- type PartMapSchema
- type PartSchema
- type PartSchemaOrSchemas
- type PartSchemas
- type PartString
- type PartStringOrStrings
- type PartStrings
- type PartValue
- type ResolveOpts
- type Schema
- func (s *Schema) Children() iter.Seq2[string, *Schema]
- func (s *Schema) Clone() *Schema
- func (s *Schema) Finalize(v *Vocabulary)
- func (s *Schema) LookupKeyword(keyword string) (PartValue, bool)
- func (s *Schema) MarshalJSON() ([]byte, error)
- func (s *Schema) MarshalJSONTo(enc *jsontext.Encoder) error
- func (s *Schema) Resolve(opts *ResolveOpts) error
- func (s *Schema) String() string
- func (s *Schema) UnmarshalJSON(data []byte) error
- func (s *Schema) UnmarshalJSONFrom(dec *jsontext.Decoder) error
- func (s *Schema) Validate(instance any) error
- func (s *Schema) ValidateInPlaceSchema(instance any, state *ValidationState) error
- func (s *Schema) ValidateSubSchema(instance any, state *ValidationState) error
- func (s *Schema) ValidateWithOpts(instance any, opts *ValidateOpts) error
- type ValidateError
- type ValidateOpts
- type ValidationError
- type ValidationErrors
- type ValidationState
- type Vocabulary
Constants ¶
This section is empty.
Variables ¶
var BoolKeyword = Keyword{ Name: "$bool", ArgType: ArgTypeBool, Validate: validateBool, }
BoolKeyword is not a real keyword, but is used to represent the special schema values "true" and "false".
var ErrInvalidSchema = errors.New("invalid schema")
ErrInvalidSchema indicates that a schema document itself is invalid: unparseable JSON, a keyword argument of the wrong type, or an unresolvable reference. It is not a validation failure of an instance, and deliberately does not match the Motmedel client-input error categories: an invalid schema is a programming error.
var SchemaKeyword = Keyword{ Name: "$schema", ArgType: ArgTypeString, Validate: validateTrue, }
SchemaKeyword is a keyword to hold the schema version.
Functions ¶
func AddValidationErrorStruct ¶
func AddValidationErrorStruct(perr *error, ve *ValidationError)
AddValidationErrorStruct adds a ValidationError to an existing error. The provided ve should already have basic fields populated. An existing error that is not a validation error is not disturbed.
func ClearVocabularies ¶
func ClearVocabularies()
ClearVocabularies discards the vocabulary registry. This is for tests.
func EnsureInstanceLocation ¶
EnsureInstanceLocation sets InstanceLocation on validation errors if empty.
func IsValidationError ¶
IsValidationError reports whether err is a validation error. This deliberately matches only direct validation error values; validation errors are aggregated, not wrapped.
func NewValidateError ¶
func NewValidateError(err error, errs []*ValidationError) error
NewValidateError returns a *ValidateError wrapping err and collecting errs.
func RegisterVocabulary ¶
func RegisterVocabulary(v *Vocabulary, def bool)
RegisterVocabulary registers a vocabulary. The def argument is true for the default vocabulary. It's normally not necessary to call this; importing a JSON schema version package will register it.
func SetDefaultSchema ¶
SetDefaultSchema sets the default schema. The argument should be something like "draft7" or "draft2020-12". This is a global property, as there is no way to pass the desired value into the JSON decoder. Callers should use appropriate locking. This is mainly for tests.
func SetLoader ¶
func SetLoader(fn func(schemaID string, uri *url.URL) (*Schema, error)) func(string, *url.URL) (*Schema, error)
SetLoader sets a function to call when resolving a $ref to an external schema. This is a global property, as there is no way to pass the desired value into the JSON decoder. Callers should use appropriate locking.
Note that when unmarshaling user-written schemas, the loader function can be called with arbitrary URIs. It's probably unwise to simply call net/http.Get in all cases.
To fully support JSON schema cross references, the loader should call SchemaFromJSON. The caller will handle calling Schema.Resolve.
This returns the old loader function. The default loader function is nil, which will produce an error for a $ref to an external schema.
Types ¶
type ArrayOrSchema ¶
type ArrayOrSchema struct {
Array []string // a zero-length slice is []string{}, not nil
Schema *Schema
}
ArrayOrSchema is the element type of the PartMapArrayOrSchema map. Exactly one of the fields will be nil.
type Keyword ¶
type Keyword struct {
// Name is the keyword, such as allOf, anyOf, and so forth.
Name string
// ArgType is the type of argument expected.
ArgType ArgType
// Validate is a function that checks whether the schema matches
// the keyword. arg is the value from the schema, which is [Part.Value].
// instance is the object to validate.
//
// The function returns an error if any.
// A failure to validate will be type [*ValidationError]
// or type [*ValidationErrors].
// Any other error type indicates a problem with the schema itself,
// not the instance.
Validate func(arg PartValue, instance any, state *ValidationState) error
// Generated is true if this keyword is not represented in JSON,
// but is added to record additional information.
// If this is true the keyword should be ignored by anything
// that wants to treat the Schema as a JSON object.
Generated bool
}
Keyword is a schema keyword.
type Part ¶
Part is one part of a JSON schema. This is a keyword, such as "$id" or "properties", along with the value associated with that keyword in the schema.
type PartAny ¶
type PartAny struct {
V any
}
PartAny is a schema part value that is an arbitrary type. For example, the schema keyword "$vocabulary" expects an object where each property is a URI. For example, the schema keyword "enum" expects an array, and matches an instance if the instance is equal to one of the elements in the array.
type PartBool ¶
type PartBool bool
PartBool is a schema part value that is a bool. This is a compact representation of a JSON schema. A value of true is the schema that matches every value. A value of false is the schema that matches no values.
type PartFloat ¶
type PartFloat float64
PartFloat is a schema part value that is a floating-point number. For example, the schema keyword "maximum" specifies the maximum value of a number.
type PartInt ¶
type PartInt int64
PartInt is a schema part value that is an integer. For example, the schema keyword "minLength" specifies the minimum length of a string.
type PartMapArrayOrSchema ¶
type PartMapArrayOrSchema map[string]ArrayOrSchema
PartMapArrayOrSchema is a map from strings to elements, where each element is either an array of strings or a schema. This is used for the draft7 "dependencies" keyword.
type PartMapSchema ¶
PartMapSchema is a schema part value that is a map from strings to schemas. For example, the schema keyword "properties" has a mapping from field names to schemas, and matches an instance if the corresponding instance fields match the schemas.
type PartSchema ¶
type PartSchema struct {
S *Schema
}
PartSchema is a schema part value that is a reference to a schema. For example, the schema keyword "not" refers to a schema; the instance matches if it does not match that schema.
type PartSchemaOrSchemas ¶
PartSchemaOrSchemas is either a single schema (like PartSchema) or a list of schemas (like PartSchemas). For example, the draft201909 keyword "items" takes either a single schema or a list of schemas. Exactly one of the fields will be nil.
type PartSchemas ¶
type PartSchemas []*Schema
PartSchemas is a schema part value that is a list of schemas. For example, the schema keyword "allOf" matches an instance if the instance matches each schema in the list.
type PartString ¶
type PartString string
PartString is a schema part value that is a string. For example, the schema keyword "pattern" has a string value that must be a regexp that must match the instance value.
type PartStringOrStrings ¶
PartStringOrStrings is a schema part that is either a single string or a list of strings. This is basically just for the "type" keyword, which takes either a single type string or an array of type strings. If the Strings is not nil, the String field must be the empty string.
type PartStrings ¶
type PartStrings []string
PartStrings is a schema part value that is a list of strings. For example, the schema keyword "required" takes a list of strings where each string is a property that the instance is required to have.
type PartValue ¶
type PartValue interface {
// contains filtered or unexported methods
}
PartValue is the value of a JSON schema element. This is accessed via a type switch. The possible types are
type ResolveOpts ¶
type ResolveOpts struct {
// The vocabulary to use.
// This overrides anything recorded with the schema.
Vocabulary *Vocabulary
// URI of root of schema.
// This is overridden by a $id keyword, if present.
URI *url.URL
// Load a remote reference, specifying the default schema.
// This will be resolved by the resolver of the schema that
// references it; no need for Loader to call (*Schema).Resolve.
Loader func(schemaID string, uri *url.URL) (*Schema, error)
}
ResolveOpts is options to use when resolving the schema. These are all optional.
type Schema ¶
type Schema struct {
// The different elements of this Schema.
Parts []Part
}
Schema is a JSON schema. A JSON schema determines whether an instance is valid or not. Do not create values of this type directly. Instead, unmarshal from JSON or use a draft-specific Builder.
If you have an existing Schema, you can edit the Parts list, but you must call Schema.Finalize afterward. When adding a new Part it will help to use Vocabulary.Keywords; each supported JSON schema draft has a Vocabulary package variable. You can't add keywords that refer to other parts of the schema by name, such as $ref.
func SchemaFromJSON ¶
SchemaFromJSON builds a Schema from a JSON value that has already been parsed. This could be used as something like
var v any
if err := json.Unmarshal(data, &v); err != nil { ... }
s, err := schema.SchemaFromJSON(schemaID, uri, v)
This can be useful in cases where it's not clear whether the JSON encoding contains a schema or not.
The optional schemaID argument is something like [draft202012.SchemaID]. The optional uri is where the schema was loaded from.
It is normally necessary to call Resolve on the result.
func (*Schema) Children ¶
Children returns an iterator over the immediate subschemas. The first iterator value is the name of the schema as used in a JSON pointer, the second is the schema itself.
func (*Schema) Finalize ¶
func (s *Schema) Finalize(v *Vocabulary)
Finalize sorts the schema keywords into the order required for validation. Normally there is no need to call this explicitly. It will be called automatically by a Builder or by the JSON unmarshaler.
func (*Schema) LookupKeyword ¶
LookupKeyword returns the value associated with a keyword in the schema. The bool result reports whether the keyword is present at all.
func (*Schema) MarshalJSON ¶
MarshalJSON marshals a Schema into JSON format. This implements encoding/json.Marshaler.
func (*Schema) MarshalJSONTo ¶
MarshalJSONTo marshals a Schema into JSON format, writing the result to enc. This implements jsonv2.MarshalerTo.
func (*Schema) Resolve ¶
func (s *Schema) Resolve(opts *ResolveOpts) error
Resolve resolves references across a schema and its subschemas. Normally there is no need to call this explicitly. It will be called automatically by the JSON unmarshaler.
func (*Schema) String ¶
String returns a somewhat readable representation of a Schema. The format differs from JSON output, and also includes internal information not stored in JSON.
func (*Schema) UnmarshalJSON ¶
UnmarshalJSON decodes the JSON representation of a Schema. This implements encoding/json.Unmarshaler.
func (*Schema) UnmarshalJSONFrom ¶
UnmarshalJSONFrom decodes the JSON representation of a Schema read from dec. This implements jsonv2.UnmarshalerFrom.
The schema is decoded directly from the JSON text, without building an intermediate representation.
func (*Schema) Validate ¶
Validate reports whether instance satisfies the schema. If it does, this returns nil. If it does not, this returns a *ValidateError that collects the individual *ValidationError values. A non-nil error of a different type indicates some error during validation processing.
func (*Schema) ValidateInPlaceSchema ¶
func (s *Schema) ValidateInPlaceSchema(instance any, state *ValidationState) error
ValidateInPlaceSchema reports whether instance satisfies schema, where schema is a subschema that is evaluated in the same context as the parent schema.
func (*Schema) ValidateSubSchema ¶
func (s *Schema) ValidateSubSchema(instance any, state *ValidationState) error
ValidateSubSchema reports whether instance satisfies schema, where schema is a sub-schema of some larger validation request. This is like Validate but also accepts the current validation state.
func (*Schema) ValidateWithOpts ¶
func (s *Schema) ValidateWithOpts(instance any, opts *ValidateOpts) error
ValidateWithOpts is like Validate but supports options.
type ValidateError ¶
type ValidateError struct {
Errors []*ValidationError
// contains filtered or unexported fields
}
ValidateError is the error returned by Schema.Validate when an instance fails validation. It wraps the underlying error and collects the individual validation errors.
func (*ValidateError) Is ¶
func (ve *ValidateError) Is(target error) bool
Is marks a ValidateError as a client-input validation failure, so that errors.Is(err, motmedelErrors.ErrValidationError) reports true.
func (*ValidateError) Unwrap ¶
func (ve *ValidateError) Unwrap() error
Unwrap returns the wrapped error.
type ValidateOpts ¶
type ValidateOpts struct {
// Whether to modify the instance being validated by setting defaults.
// If this is true, then defaults are applied when:
// - a "properties" keyword is applied to a map or a struct
// - a "prefixItems" keyword is applied to a slice or array
// - a "items" keyword with an array argument (pre draft2020-12)
// is applied to a slice or array.
// In these cases, if the subschema has a "default" keyword,
// and the value in question is the zero value of its type
// (or, in the case of a map, is missing), then the instance
// is modified to be set to the default.
// Defaults are ignored for required properties,
// as the user must supply them.
//
// This operation may panic if the instance can't be modified.
//
// The modification is made before validation;
// if the default value is not permitted by the rest of
// the schema, validation may fail.
ApplyDefaults bool
// Whether to validate the format keyword.
// In order for this to be effective, the package
// jsonschema/format must be blank imported;
// by default the format keyword always matches.
ValidateFormat bool
}
ValidateOpts describes validation options. These are uncommon so we use a separate method for them.
type ValidationError ¶
type ValidationError struct {
// Basic output fields per JSON Schema output format (basic):
// https://json-schema.org/draft/2020-12/json-schema-core.html#name-output-formats
// These are the canonical fields consumers should use.
Message string `json:"error"`
KeywordLocation string `json:"keywordLocation"`
InstanceLocation string `json:"instanceLocation"`
}
ValidationError is returned by a validation function when an instance fails validation.
func (*ValidationError) Error ¶
func (ve *ValidationError) Error() string
Error returns the error message that a user should see. This implements the error interface.
type ValidationErrors ¶
type ValidationErrors struct {
Errs []*ValidationError
}
ValidationErrors is a collection of ValidationError values.
func (*ValidationErrors) Error ¶
func (ves *ValidationErrors) Error() string
Error returns the error message that a user should see. This implements the error interface.
type ValidationState ¶
type ValidationState struct {
// The root of the Schema being validated.
Root *Schema
// The ValidationState attached to the root Schema,
// for global information.
RootState *ValidationState
// The Schema being validated.
Schema *Schema
// The index in schema.Parts of the keyword currently being validated.
Index int
// Current URI, from $id keyword.
URI *url.URL
// Notes created during validation.
Notes notes.Notes
// Depth of tree when validating. Used to avoid infinite recursion.
Depth int
// Validation options. Nil for the defaults.
Opts *ValidateOpts
// For use by version-specific code.
VersionData *any
// InstancePath holds the JSON Pointer tokens to the current location
// within the instance being validated.
InstancePath []string
}
ValidationState is state we maintain while validating a schema. This does not apply to subschemas or parent schemas. This is exported for use by additional schema implementations. It is not expected to be used by code that just wants to validate a schema.
func (*ValidationState) Child ¶
func (vs *ValidationState) Child() (*ValidationState, error)
Child returns a new ValidationState that is a child of vs. This can be used to validate a subschema without changing the notes stored in vs.
func (*ValidationState) InstancePointer ¶
func (vs *ValidationState) InstancePointer() string
InstancePointer returns the current instance location as a JSON Pointer string starting with '#'.
func (*ValidationState) PopInstanceToken ¶
func (vs *ValidationState) PopInstanceToken()
PopInstanceToken removes the last token from the instance path.
func (*ValidationState) PushInstanceToken ¶
func (vs *ValidationState) PushInstanceToken(tok string)
PushInstanceToken appends a token to the instance path.
type Vocabulary ¶
type Vocabulary struct {
// The name of this schema version, for messages.
// Something like draft-2020-12.
Name string
// The URI that describes this schema version.
// The value of the $schema keyword.
// Something like "https://json-schema.org/draft/2020-12/schema".
Schema string
// The keywords of this schema version.
Keywords map[string]*Keyword
// A function that resolves references within a schema.
Resolve func(*Schema, *ResolveOpts) error
// The sorting function of this schema.
// Used to sort the keywords of an instance of the schema.
Cmp func(string, string) int
}
Vocabulary is a vocabulary type: a list of known keywords. Each schema version defines an instance of this type.
func DefaultVocabulary ¶
func DefaultVocabulary() *Vocabulary
DefaultVocabulary returns the default vocabulary, or nil if there isn't one.
func LookupVocabulary ¶
func LookupVocabulary(s string) *Vocabulary
LookupVocabulary returns a registered vocabulary, or nil if no vocabulary was registered under that name. It's normally not necessary to call this; instead use something like draft202012.Vocabulary.