Documentation
¶
Overview ¶
Package jsonschema implements a high-performance JSON Schema Draft 2020-12 validator for Go, providing direct struct validation, smart unmarshaling with defaults, and a separated validation workflow.
Credit to https://github.com/santhosh-tekuri/jsonschema for format validators.
Example (ArraySchema) ¶
package main
import (
"fmt"
"github.com/kaptinlin/jsonschema"
)
func main() {
// Array schema with validation keywords
numbersSchema := jsonschema.Array(
jsonschema.Items(jsonschema.Number(
jsonschema.Min(0),
jsonschema.Max(100),
)),
jsonschema.MinItems(1),
jsonschema.MaxItems(10),
)
validData := []any{10, 20, 30}
result := numbersSchema.Validate(validData)
fmt.Println("Numbers valid:", result.IsValid())
invalidData := []any{-5, 150} // Out of range
result = numbersSchema.Validate(invalidData)
fmt.Println("Invalid numbers valid:", result.IsValid())
}
Output: Numbers valid: true Invalid numbers valid: false
Example (CompatibilityWithJSON) ¶
package main
import (
"fmt"
"log"
"github.com/kaptinlin/jsonschema"
)
func main() {
// New code construction approach
codeSchema := jsonschema.Object(
jsonschema.Prop("name", jsonschema.String()),
jsonschema.Prop("age", jsonschema.Integer()),
)
// Existing JSON compilation approach
compiler := jsonschema.NewCompiler()
jsonSchema, err := compiler.Compile([]byte(`{
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"}
}
}`))
if err != nil {
log.Fatal(err)
}
data := map[string]any{
"name": "Bob",
"age": 25,
}
// Both approaches work identically
result1 := codeSchema.Validate(data)
result2 := jsonSchema.Validate(data)
fmt.Println("Code schema valid:", result1.IsValid())
fmt.Println("JSON schema valid:", result2.IsValid())
}
Output: Code schema valid: true JSON schema valid: true
Example (ComplexSchema) ¶
package main
import (
"fmt"
"github.com/kaptinlin/jsonschema"
)
func main() {
// Complex nested schema with validation keywords
userSchema := jsonschema.Object(
jsonschema.Prop("name", jsonschema.String(
jsonschema.MinLen(1),
jsonschema.MaxLen(100),
)),
jsonschema.Prop("age", jsonschema.Integer(
jsonschema.Min(0),
jsonschema.Max(150),
)),
jsonschema.Prop("email", jsonschema.Email()),
jsonschema.Prop("address", jsonschema.Object(
jsonschema.Prop("street", jsonschema.String(jsonschema.MinLen(1))),
jsonschema.Prop("city", jsonschema.String(jsonschema.MinLen(1))),
jsonschema.Prop("zip", jsonschema.String(jsonschema.Pattern(`^\d{5}$`))),
jsonschema.Required("street", "city"),
)),
jsonschema.Prop("tags", jsonschema.Array(
jsonschema.Items(jsonschema.String()),
jsonschema.MinItems(1),
jsonschema.UniqueItems(true),
)),
jsonschema.Required("name", "email"),
)
// Test data
userData := map[string]any{
"name": "Alice",
"age": 30,
"email": "alice@example.com",
"address": map[string]any{
"street": "123 Main St",
"city": "Anytown",
"zip": "12345",
},
"tags": []any{"developer", "go"},
}
result := userSchema.Validate(userData)
if result.IsValid() {
fmt.Println("User data is valid")
} else {
for field, err := range result.Errors {
fmt.Printf("Error in %s: %s\n", field, err.Message)
}
}
}
Output: User data is valid
Example (ConditionalSchema) ¶
package main
import (
"fmt"
"github.com/kaptinlin/jsonschema"
)
func main() {
// Conditional schema using if/then/else keywords
conditionalSchema := jsonschema.If(
jsonschema.Object(
jsonschema.Prop("type", jsonschema.Const("premium")),
),
).Then(
jsonschema.Object(
jsonschema.Prop("features", jsonschema.Array(jsonschema.MinItems(5))),
),
).Else(
jsonschema.Object(
jsonschema.Prop("features", jsonschema.Array(jsonschema.MaxItems(3))),
),
)
// Basic plan object
basicPlan := map[string]any{
"type": "basic",
"features": []any{"feature1", "feature2"},
}
result := conditionalSchema.Validate(basicPlan)
fmt.Println("Basic plan valid:", result.IsValid())
}
Output: Basic plan valid: true
Example (ConvenienceFunctions) ¶
package main
import (
"fmt"
"github.com/kaptinlin/jsonschema"
)
func main() {
// Using convenience functions that apply format keywords
profileSchema := jsonschema.Object(
jsonschema.Prop("id", jsonschema.UUID()),
jsonschema.Prop("email", jsonschema.Email()),
jsonschema.Prop("website", jsonschema.URI()),
jsonschema.Prop("created", jsonschema.DateTime()),
jsonschema.Prop("score", jsonschema.PositiveInt()),
)
data := map[string]any{
"id": "550e8400-e29b-41d4-a716-446655440000",
"email": "user@example.com",
"website": "https://example.com",
"created": "2023-01-01T00:00:00Z",
"score": 95,
}
result := profileSchema.Validate(data)
fmt.Println("Profile valid:", result.IsValid())
}
Output: Profile valid: true
Example (EnumAndConst) ¶
package main
import (
"fmt"
"github.com/kaptinlin/jsonschema"
)
func main() {
// Enum schema using enum keyword
statusSchema := jsonschema.Enum("active", "inactive", "pending")
result := statusSchema.Validate("active")
fmt.Println("Status valid:", result.IsValid())
// Const schema using const keyword
versionSchema := jsonschema.Const("1.0.0")
result = versionSchema.Validate("1.0.0")
fmt.Println("Version valid:", result.IsValid())
}
Output: Status valid: true Version valid: true
Example (Object) ¶
package main
import (
"fmt"
"github.com/kaptinlin/jsonschema"
)
func main() {
// Simple object schema using constructor API
schema := jsonschema.Object(
jsonschema.Prop("name", jsonschema.String(jsonschema.MinLen(1))),
jsonschema.Prop("age", jsonschema.Integer(jsonschema.Min(0))),
jsonschema.Required("name"),
)
// Valid data
data := map[string]any{
"name": "Alice",
"age": 30,
}
result := schema.Validate(data)
fmt.Println("Valid:", result.IsValid())
}
Output: Valid: true
Example (OneOfAnyOf) ¶
package main
import (
"fmt"
"github.com/kaptinlin/jsonschema"
)
func main() {
// OneOf: exactly one schema must match
oneOfSchema := jsonschema.OneOf(
jsonschema.String(),
jsonschema.Integer(),
)
result := oneOfSchema.Validate("hello")
fmt.Println("OneOf string valid:", result.IsValid())
// AnyOf: at least one schema must match
anyOfSchema := jsonschema.AnyOf(
jsonschema.String(jsonschema.MinLen(5)),
jsonschema.Integer(jsonschema.Min(0)),
)
result = anyOfSchema.Validate("hi") // Matches integer rule (length < 5 but is string)
fmt.Println("AnyOf short string valid:", result.IsValid())
}
Output: OneOf string valid: true AnyOf short string valid: false
Example (SchemaRegistration) ¶
package main
import (
"fmt"
"log"
"github.com/kaptinlin/jsonschema"
)
func main() {
// Create compiler for schema registration
compiler := jsonschema.NewCompiler()
// Create User schema with Constructor API
userSchema := jsonschema.Object(
jsonschema.ID("https://example.com/schemas/user"),
jsonschema.Prop("id", jsonschema.UUID()),
jsonschema.Prop("name", jsonschema.String(jsonschema.MinLen(1))),
jsonschema.Prop("email", jsonschema.Email()),
jsonschema.Required("id", "name", "email"),
)
// Register the schema
compiler.SetSchema("https://example.com/schemas/user", userSchema)
// Create Profile schema that references User schema
profileJSON := `{
"type": "object",
"properties": {
"user": {"$ref": "https://example.com/schemas/user"},
"bio": {"type": "string"},
"website": {"type": "string", "format": "uri"}
},
"required": ["user"]
}`
profileSchema, err := compiler.Compile([]byte(profileJSON))
if err != nil {
log.Fatal(err)
}
// Test with valid data
profileData := map[string]any{
"user": map[string]any{
"id": "550e8400-e29b-41d4-a716-446655440000",
"name": "Alice Johnson",
"email": "alice@example.com",
},
"bio": "Software engineer",
"website": "https://alice.dev",
}
result := profileSchema.Validate(profileData)
fmt.Println("Profile with registered user schema valid:", result.IsValid())
}
Output: Profile with registered user schema valid: true
Index ¶
- Constants
- Variables
- func CacheStats() map[string]int
- func ClearSchemaCache()
- func DefaultNowFunc(args ...any) (any, error)
- func FormatRat(r *Rat) string
- func I18n() (*i18n.I18n, error)
- func IsDate(v any) bool
- func IsDateTime(v any) bool
- func IsDuration(v any) bool
- func IsEmail(v any) bool
- func IsHostname(v any) bool
- func IsIPV4(v any) bool
- func IsIPV6(v any) bool
- func IsJSONPointer(v any) bool
- func IsPeriod(v any) bool
- func IsRegex(v any) bool
- func IsRelativeJSONPointer(v any) bool
- func IsTime(v any) bool
- func IsURI(v any) bool
- func IsURIReference(v any) bool
- func IsURITemplate(v any) bool
- func IsUUID(v any) bool
- func RegisterCustomValidator(name string, validator CustomValidatorFunc)
- func SetDefaultCompiler(c *Compiler)
- type Compiler
- func (c *Compiler) Compile(jsonSchema []byte, uris ...string) (*Schema, error)
- func (c *Compiler) CompileBatch(schemas map[string][]byte) (map[string]*Schema, error)
- func (c *Compiler) RegisterDecoder(encodingName string, decoderFunc func(string) ([]byte, error)) *Compiler
- func (c *Compiler) RegisterDefaultFunc(name string, fn DefaultFunc) *Compiler
- func (c *Compiler) RegisterFormat(name string, validator func(any) bool, typeName ...string) *Compiler
- func (c *Compiler) RegisterLoader(scheme string, loaderFunc func(url string) (io.ReadCloser, error)) *Compiler
- func (c *Compiler) RegisterMediaType(mediaTypeName string, unmarshalFunc func([]byte) (any, error)) *Compiler
- func (c *Compiler) Schema(ref string) (*Schema, error)
- func (c *Compiler) SetAssertFormat(assert bool) *Compiler
- func (c *Compiler) SetDefaultBaseURI(baseURI string) *Compiler
- func (c *Compiler) SetPreserveExtra(preserve bool) *Compiler
- func (c *Compiler) SetSchema(uri string, schema *Schema) *Compiler
- func (c *Compiler) UnregisterFormat(name string) *Compiler
- func (c *Compiler) WithDecoderJSON(decoder func(data []byte, v any) error) *Compiler
- func (c *Compiler) WithEncoderJSON(encoder func(v any) ([]byte, error)) *Compiler
- type ConditionalSchema
- type ConstValue
- type CustomValidatorFunc
- type DefaultFunc
- type DynamicScope
- func (ds *DynamicScope) Contains(schema *Schema) bool
- func (ds *DynamicScope) IsEmpty() bool
- func (ds *DynamicScope) LookupDynamicAnchor(anchor string) *Schema
- func (ds *DynamicScope) Peek() *Schema
- func (ds *DynamicScope) Pop() *Schema
- func (ds *DynamicScope) Push(schema *Schema)
- func (ds *DynamicScope) Size() int
- type EvaluationError
- type EvaluationResult
- func (e *EvaluationResult) AddAnnotation(keyword string, annotation any) *EvaluationResult
- func (e *EvaluationResult) AddDetail(detail *EvaluationResult) *EvaluationResult
- func (e *EvaluationResult) AddError(err *EvaluationError) *EvaluationResult
- func (e *EvaluationResult) CollectAnnotations() *EvaluationResult
- func (e *EvaluationResult) DetailedErrors(localizer ...*i18n.Localizer) map[string]string
- func (e *EvaluationResult) Error() string
- func (e *EvaluationResult) IsValid() bool
- func (e *EvaluationResult) SetEvaluationPath(evaluationPath string) *EvaluationResult
- func (e *EvaluationResult) SetInstanceLocation(instanceLocation string) *EvaluationResult
- func (e *EvaluationResult) SetInvalid() *EvaluationResult
- func (e *EvaluationResult) SetSchemaLocation(location string) *EvaluationResult
- func (e *EvaluationResult) ToFlag() *Flag
- func (e *EvaluationResult) ToList(includeHierarchy ...bool) *List
- func (e *EvaluationResult) ToLocalizeList(localizer *i18n.Localizer, includeHierarchy ...bool) *List
- type FieldCache
- type FieldInfo
- type Flag
- type FormatDef
- type FunctionCall
- type Keyword
- func AdditionalProps(allowed bool) Keyword
- func AdditionalPropsSchema(schema *Schema) Keyword
- func Anchor(anchor string) Keyword
- func Contains(schema *Schema) Keyword
- func ContentEncoding(encoding string) Keyword
- func ContentMediaType(mediaType string) Keyword
- func ContentSchema(schema *Schema) Keyword
- func Default(value any) Keyword
- func Defs(defs map[string]*Schema) Keyword
- func DependentRequired(dependencies map[string][]string) Keyword
- func DependentSchemas(dependencies map[string]*Schema) Keyword
- func Deprecated(deprecated bool) Keyword
- func Description(desc string) Keyword
- func DynamicAnchor(anchor string) Keyword
- func Examples(examples ...any) Keyword
- func ExclusiveMax(maxVal float64) Keyword
- func ExclusiveMin(minVal float64) Keyword
- func Format(format string) Keyword
- func ID(id string) Keyword
- func Items(itemSchema *Schema) Keyword
- func Max(maxVal float64) Keyword
- func MaxContains(maxContains int) Keyword
- func MaxItems(maxItems int) Keyword
- func MaxLen(maxLen int) Keyword
- func MaxProps(maxProps int) Keyword
- func Min(minVal float64) Keyword
- func MinContains(minContains int) Keyword
- func MinItems(minItems int) Keyword
- func MinLen(minLen int) Keyword
- func MinProps(minProps int) Keyword
- func MultipleOf(multiple float64) Keyword
- func Pattern(pattern string) Keyword
- func PatternProps(patterns map[string]*Schema) Keyword
- func PrefixItems(schemas ...*Schema) Keyword
- func PropertyNames(schema *Schema) Keyword
- func ReadOnly(readOnly bool) Keyword
- func Required(fields ...string) Keyword
- func SchemaURI(schemaURI string) Keyword
- func Title(title string) Keyword
- func UnevaluatedItems(schema *Schema) Keyword
- func UnevaluatedProps(schema *Schema) Keyword
- func UniqueItems(unique bool) Keyword
- func WriteOnly(writeOnly bool) Keyword
- type List
- type Property
- type Rat
- type RegexPatternError
- type RequiredSort
- type Schema
- func AllOf(schemas ...*Schema) *Schema
- func Any(keywords ...Keyword) *Schema
- func AnyOf(schemas ...*Schema) *Schema
- func Array(keywords ...Keyword) *Schema
- func Boolean(keywords ...Keyword) *Schema
- func Const(value any) *Schema
- func Date() *Schema
- func DateTime() *Schema
- func Duration() *Schema
- func Email() *Schema
- func Enum(values ...any) *Schema
- func FromStruct[T any]() (*Schema, error)
- func FromStructWithOptions[T any](options *StructTagOptions) (*Schema, error)
- func Hostname() *Schema
- func IPv4() *Schema
- func IPv6() *Schema
- func IRI() *Schema
- func IRIRef() *Schema
- func IdnEmail() *Schema
- func IdnHostname() *Schema
- func Integer(keywords ...Keyword) *Schema
- func JSONPointer() *Schema
- func NegativeInt() *Schema
- func NonNegativeInt() *Schema
- func NonPositiveInt() *Schema
- func Not(schema *Schema) *Schema
- func Null(keywords ...Keyword) *Schema
- func Number(keywords ...Keyword) *Schema
- func Object(items ...any) *Schema
- func OneOf(schemas ...*Schema) *Schema
- func PositiveInt() *Schema
- func Ref(ref string) *Schema
- func Regex() *Schema
- func RelativeJSONPointer() *Schema
- func String(keywords ...Keyword) *Schema
- func Time() *Schema
- func URI() *Schema
- func URIRef() *Schema
- func URITemplate() *Schema
- func UUID() *Schema
- func (s *Schema) Compiler() *Compiler
- func (s *Schema) MarshalJSON() ([]byte, error)
- func (s *Schema) MarshalJSONTo(enc *jsontext.Encoder, opts json.Options) error
- func (s *Schema) ResolveUnresolvedReferences()
- func (s *Schema) SchemaLocation(anchor string) string
- func (s *Schema) SchemaURI() string
- func (s *Schema) SetCompiler(compiler *Compiler) *Schema
- func (s *Schema) Unmarshal(dst, src any) error
- func (s *Schema) UnmarshalJSON(data []byte) error
- func (s *Schema) UnresolvedReferenceURIs() []string
- func (s *Schema) Validate(instance any) *EvaluationResult
- func (s *Schema) ValidateJSON(data []byte) *EvaluationResult
- func (s *Schema) ValidateMap(data map[string]any) *EvaluationResult
- func (s *Schema) ValidateStruct(instance any) *EvaluationResult
- type SchemaMap
- type SchemaType
- type StructTagError
- type StructTagOptions
- type UnmarshalError
- type ValidatorRegistry
Examples ¶
Constants ¶
const ( // FormatEmail represents the email format validation. FormatEmail = "email" // FormatDateTime represents the date-time format (RFC 3339). FormatDateTime = "date-time" // FormatDate represents the date format (RFC 3339 full-date). FormatDate = "date" // FormatTime represents the time format (RFC 3339 full-time). FormatTime = "time" // FormatURI represents the URI format (RFC 3986). FormatURI = "uri" // FormatURIRef represents the URI-reference format (RFC 3986). FormatURIRef = "uri-reference" // FormatUUID represents the UUID format (RFC 4122). FormatUUID = "uuid" // FormatHostname represents the hostname format (RFC 1123). FormatHostname = "hostname" // FormatIPv4 represents the IPv4 address format (RFC 2673). FormatIPv4 = "ipv4" // FormatIPv6 represents the IPv6 address format (RFC 4291). FormatIPv6 = "ipv6" // FormatRegex represents the ECMA-262 regular expression format. FormatRegex = "regex" // FormatIdnEmail represents the internationalized email format (RFC 6531). FormatIdnEmail = "idn-email" // FormatIdnHostname represents the internationalized hostname format (RFC 5890). FormatIdnHostname = "idn-hostname" // FormatIRI represents the IRI format (RFC 3987). FormatIRI = "iri" // FormatIRIRef represents the IRI-reference format (RFC 3987). FormatIRIRef = "iri-reference" // FormatURITemplate represents the URI template format (RFC 6570). FormatURITemplate = "uri-template" // FormatJSONPointer represents the JSON Pointer format (RFC 6901). FormatJSONPointer = "json-pointer" // FormatRelativeJSONPointer represents the relative JSON Pointer format. FormatRelativeJSONPointer = "relative-json-pointer" // FormatDuration represents the duration format (RFC 3339 appendix A / ISO 8601). FormatDuration = "duration" )
Format validation constants define the standard format names from JSON Schema Draft 2020-12.
Variables ¶
var ( // ErrNoLoaderRegistered is returned when no loader is registered for the specified scheme. ErrNoLoaderRegistered = errors.New("no loader registered for scheme") // ErrDataRead is returned when data cannot be read from the specified URL. ErrDataRead = errors.New("data read failed") // Former: ErrFailedToReadData // ErrNetworkFetch is returned when there is an error fetching from the URL. ErrNetworkFetch = errors.New("network fetch failed") // Former: ErrFailedToFetch // ErrInvalidStatusCode is returned when an invalid HTTP status code is returned. ErrInvalidStatusCode = errors.New("invalid http status code") // Former: ErrInvalidHTTPStatusCode // ErrFileWrite is returned when file writing fails. ErrFileWrite = errors.New("file write failed") // Former: ErrFailedToWriteFile // ErrFileCreation is returned when file creation fails. ErrFileCreation = errors.New("file creation failed") // Former: ErrFailedToCreateFile // ErrDirectoryCreation is returned when directory creation fails. ErrDirectoryCreation = errors.New("directory creation failed") // Former: ErrFailedToCreateDirectory // ErrContentWrite is returned when writing content to file fails. ErrContentWrite = errors.New("content write failed") // Former: ErrFailedToWriteContent // ErrInvalidFilenamePath is returned when filename path is invalid. ErrInvalidFilenamePath = errors.New("invalid filename path") )
=== Network and IO Related Errors ===
var ( // ErrJSONUnmarshal is returned when there is an error unmarshalling JSON. ErrJSONUnmarshal = errors.New("json unmarshal failed") // Former: ErrJSONUnmarshalError // ErrXMLUnmarshal is returned when there is an error unmarshalling XML. ErrXMLUnmarshal = errors.New("xml unmarshal failed") // Former: ErrXMLUnmarshalError // ErrYAMLUnmarshal is returned when there is an error unmarshalling YAML. ErrYAMLUnmarshal = errors.New("yaml unmarshal failed") // Former: ErrYAMLUnmarshalError // ErrJSONDecode is returned when JSON decoding fails. ErrJSONDecode = errors.New("json decode failed") // Former: ErrFailedToDecodeJSON // ErrSourceEncode is returned when source encoding fails. ErrSourceEncode = errors.New("source encode failed") // Former: ErrFailedToEncodeSource // ErrIntermediateJSONDecode is returned when intermediate JSON decoding fails. ErrIntermediateJSONDecode = errors.New("intermediate json decode failed") // Former: ErrFailedToDecodeIntermediateJSON // ErrDataEncode is returned when data encoding fails. ErrDataEncode = errors.New("data encode failed") // Former: ErrFailedToEncodeData // ErrNestedValueEncode is returned when encoding nested values fails. ErrNestedValueEncode = errors.New("nested value encode failed") // Former: ErrFailedToEncodeNestedValue )
=== Serialization Related Errors ===
var ( // ErrSchemaCompilation is returned when a schema compilation fails. ErrSchemaCompilation = errors.New("schema compilation failed") // Former: ErrFailedToCompileSchema // ErrReferenceResolution is returned when a reference cannot be resolved. ErrReferenceResolution = errors.New("reference resolution failed") // Former: ErrFailedToResolveReference // ErrGlobalReferenceResolution is returned when a global reference cannot be resolved. ErrGlobalReferenceResolution = errors.New("global reference resolution failed") // Former: ErrFailedToResolveGlobalReference // ErrDefinitionResolution is returned when definitions in $defs cannot be resolved. ErrDefinitionResolution = errors.New("definition resolution failed") // Former: ErrFailedToResolveDefinitions // ErrItemResolution is returned when items in an array schema cannot be resolved. ErrItemResolution = errors.New("item resolution failed") // Former: ErrFailedToResolveItems // ErrJSONPointerSegmentDecode is returned when a segment cannot be decoded. ErrJSONPointerSegmentDecode = errors.New("json pointer segment decode failed") // Former: ErrFailedToDecodeSegmentWithJSONPointer // ErrJSONPointerSegmentNotFound is returned when a segment is not found in the schema context. ErrJSONPointerSegmentNotFound = errors.New("json pointer segment not found") // Former: ErrSegmentNotFoundForJSONPointer // ErrInvalidSchemaType is returned when the JSON schema type is invalid. ErrInvalidSchemaType = errors.New("invalid schema type") // Former: ErrInvalidJSONSchemaType // ErrSchemaIsNil is returned when schema is nil. ErrSchemaIsNil = errors.New("schema is nil") // ErrSchemaInternalsIsNil is returned when schema internals is nil. ErrSchemaInternalsIsNil = errors.New("schema internals is nil") // ErrRegexValidation is returned when regex pattern validation fails. ErrRegexValidation = errors.New("regex validation failed") )
=== Schema Compilation and Parsing Related Errors ===
var ( // ErrValueValidationFailed is returned when value validation fails. ErrValueValidationFailed = errors.New("value validation failed") // ErrInvalidRuleFormat is returned when rule format is invalid. ErrInvalidRuleFormat = errors.New("invalid rule format") // ErrRuleRequiresParameter is returned when a rule requires a parameter. ErrRuleRequiresParameter = errors.New("rule requires parameter") // ErrEmptyRuleName is returned when rule name is empty. ErrEmptyRuleName = errors.New("empty rule name") // ErrValidatorAlreadyExists is returned when a validator with the same name already exists. ErrValidatorAlreadyExists = errors.New("validator already exists") )
=== Data Validation Related Errors ===
var ( // Basic type conversion // ErrTypeConversion is returned when type conversion fails. ErrTypeConversion = errors.New("type conversion failed") // ErrTimeConversion is returned when time conversion fails. ErrTimeConversion = errors.New("time conversion failed") // Former: ErrTimeTypeConversion // ErrTimeParsing is returned when time parsing fails. ErrTimeParsing = errors.New("time parsing failed") // Former: ErrTimeParseFailure // ErrRatConversion is returned when rat conversion fails. ErrRatConversion = errors.New("rat conversion failed") // Former: ErrFailedToConvertToRat // Collection type conversion // ErrSliceConversion is returned when slice conversion fails. ErrSliceConversion = errors.New("slice conversion failed") // Former: ErrCannotConvertSlice // ErrSliceElementConversion is returned when slice element conversion fails. ErrSliceElementConversion = errors.New("slice element conversion failed") // Former: ErrCannotConvertSliceElement // ErrFirstSliceConversion is returned when first slice conversion fails. ErrFirstSliceConversion = errors.New("first slice conversion failed") // Former: ErrCannotConvertFirstSlice // ErrSecondSliceConversion is returned when second slice conversion fails. ErrSecondSliceConversion = errors.New("second slice conversion failed") // Former: ErrCannotConvertSecondSlice // ErrNilConversion is returned when nil conversion fails. ErrNilConversion = errors.New("nil conversion failed") // Former: ErrCannotConvertNil // ErrNilPointerConversion is returned when nil pointer conversion fails. ErrNilPointerConversion = errors.New("nil pointer conversion failed") // Former: ErrCannotConvertNilPointer // ErrValueParsing is returned when value parsing fails. ErrValueParsing = errors.New("value parsing failed") // Former: ErrCannotParseValue // ErrValueAssignment is returned when value assignment fails. ErrValueAssignment = errors.New("value assignment failed") // Former: ErrCannotAssignValue // Specific type support // ErrUnsupportedType is returned when an unsupported type is encountered. ErrUnsupportedType = errors.New("unsupported type") // ErrUnsupportedRatType is returned when the type is unsupported for conversion to *big.Rat. ErrUnsupportedRatType = errors.New("unsupported rat type") // Former: ErrUnsupportedTypeForRat // ErrUnsupportedInputType is returned when an unsupported input type is encountered. ErrUnsupportedInputType = errors.New("unsupported input type") // ErrUnsupportedGenerationType is returned when an unsupported type is encountered during code generation. ErrUnsupportedGenerationType = errors.New("unsupported generation type") // Former: ErrUnsupportedTypeForGeneration // ErrUnsupportedConversion is returned when conversion is not supported. ErrUnsupportedConversion = errors.New("unsupported conversion") // ErrUnrepresentableType is returned when a type cannot be represented. ErrUnrepresentableType = errors.New("unrepresentable type") // ErrInvalidTransformType is returned when type is invalid for transform. ErrInvalidTransformType = errors.New("invalid transform type") // Former: ErrInvalidTypeForTransform )
=== Type Conversion Related Errors ===
var ( // ErrExpectedStructType is returned when a non-struct type is provided where a struct type is expected. ErrExpectedStructType = errors.New("expected struct type") // ErrStructTagParsing is returned when struct tags cannot be parsed. ErrStructTagParsing = errors.New("struct tag parsing failed") // Former: ErrFailedToParseStructTags // ErrFieldNotFound is returned when field is not found. ErrFieldNotFound = errors.New("field not found") // ErrFieldAssignment is returned when field assignment fails. ErrFieldAssignment = errors.New("field assignment failed") // Former: ErrFailedToSetField // ErrFieldAnalysis is returned when field analysis fails. ErrFieldAnalysis = errors.New("field analysis failed") // Former: ErrFailedToAnalyzeFields // ErrNilDestination is returned when destination cannot be nil. ErrNilDestination = errors.New("destination cannot be nil") // ErrNotPointer is returned when destination must be a pointer. ErrNotPointer = errors.New("destination must be a pointer") // ErrNilPointer is returned when destination pointer cannot be nil. ErrNilPointer = errors.New("destination pointer cannot be nil") )
=== Struct and Reflection Related Errors ===
var ( // ErrDefaultApplication is returned when applying defaults fails. ErrDefaultApplication = errors.New("default application failed") // Former: ErrFailedToApplyDefaults // ErrDefaultEvaluation is returned when evaluating default values fails. ErrDefaultEvaluation = errors.New("default evaluation failed") // Former: ErrFailedToEvaluateDefaultValue // ErrArrayDefaultApplication is returned when applying array defaults fails. ErrArrayDefaultApplication = errors.New("array default application failed") // Former: ErrFailedToApplyArrayDefaults // ErrFunctionCallParsing is returned when parsing function calls fails. ErrFunctionCallParsing = errors.New("function call parsing failed") // Former: ErrFailedToParseFunctionCall )
=== Default Value Handling Related Errors ===
var ( // ErrNilConfig is returned when a configuration is nil. ErrNilConfig = errors.New("config cannot be nil") // Former: ErrConfigCannotBeNil // ErrAnalyzerCreation is returned when analyzer creation fails. ErrAnalyzerCreation = errors.New("analyzer creation failed") // Former: ErrFailedToCreateAnalyzer // ErrWriterCreation is returned when writer creation fails. ErrWriterCreation = errors.New("writer creation failed") // Former: ErrFailedToCreateWriter // ErrPackageAnalysis is returned when package analysis fails. ErrPackageAnalysis = errors.New("package analysis failed") // Former: ErrFailedToAnalyzePackage // ErrCodeGeneration is returned when code generation fails. ErrCodeGeneration = errors.New("code generation failed") // Former: ErrFailedToGenerateCode // ErrPropertyGeneration is returned when property generation fails. ErrPropertyGeneration = errors.New("property generation failed") // Former: ErrFailedToGenerateProperty // ErrJSONSchemaTagParsing is returned when jsonschema tag parsing fails. ErrJSONSchemaTagParsing = errors.New("json schema tag parsing failed") // Former: ErrFailedToParseJSONSchemaTag // ErrGozodTagParsing is returned when gozod tag parsing fails. ErrGozodTagParsing = errors.New("gozod tag parsing failed") // Former: ErrFailedToParseGozodTag // ErrTemplateLoading is returned when template loading fails. ErrTemplateLoading = errors.New("template loading failed") // Former: ErrFailedToLoadTemplates // ErrOutputDirectoryCreation is returned when output directory creation fails. ErrOutputDirectoryCreation = errors.New("output directory creation failed") // Former: ErrFailedToCreateOutputDirectory // ErrFieldSchemaGeneration is returned when field schema generation fails. ErrFieldSchemaGeneration = errors.New("field schema generation failed") // Former: ErrFailedToGenerateFieldSchemas // ErrTemplateExecution is returned when template execution fails. ErrTemplateExecution = errors.New("template execution failed") // Former: ErrFailedToExecuteTemplate // ErrMainTemplateParsing is returned when main template parsing fails. ErrMainTemplateParsing = errors.New("main template parsing failed") // Former: ErrFailedToParseMainTemplate // ErrDependencyAnalysis is returned when dependency analysis fails. ErrDependencyAnalysis = errors.New("dependency analysis failed") // Former: ErrFailedToAnalyzeDependencies // ErrTemplateParsing is returned when template parsing fails. ErrTemplateParsing = errors.New("template parsing failed") // Former: ErrFailedToParseTemplate // ErrCodeFormatting is returned when code formatting fails. ErrCodeFormatting = errors.New("code formatting failed") // Former: ErrFailedToFormatCode // ErrStructNodeNotFound is returned when a struct node cannot be found. ErrStructNodeNotFound = errors.New("struct node not found") )
=== Code Generation Related Errors ===
var ( // ErrArrayItemNotSchema is returned when an array item is not a schema. ErrArrayItemNotSchema = errors.New("array item not schema") // ErrExpectedArrayOrSlice is returned when array or slice is expected. ErrExpectedArrayOrSlice = errors.New("expected array or slice") // ErrNilPointerToArray is returned when trying to convert nil pointer to array. ErrNilPointerToArray = errors.New("nil pointer to array") // ErrNilPointerToRecord is returned when trying to convert nil pointer to record. ErrNilPointerToRecord = errors.New("nil pointer to record") // ErrNilPointerToObject is returned when trying to convert nil pointer to object. ErrNilPointerToObject = errors.New("nil pointer to object") // ErrExpectedMapStringAny is returned when map[string]any is expected. ErrExpectedMapStringAny = errors.New("expected map[string]any") // ErrNonStringKeyFound is returned when non-string key is found in map. ErrNonStringKeyFound = errors.New("non-string key found in map") )
=== Array and Object Related Errors ===
var ( // ErrValueOverflows is returned when value overflows target type. ErrValueOverflows = errors.New("value overflows target type") // ErrEmptyInput is returned when input is empty. ErrEmptyInput = errors.New("empty input") // ErrNegativeValueConversion is returned when negative value cannot be converted. ErrNegativeValueConversion = errors.New("negative value conversion failed") // Former: ErrNegativeValue // ErrNonWholeNumber is returned when value is not a whole number. ErrNonWholeNumber = errors.New("not a whole number") // Former: ErrNotWholeNumber // ErrInvalidSliceArrayString is returned when input is not a slice, array, or string. ErrInvalidSliceArrayString = errors.New("invalid slice array string") // Former: ErrNotSliceArrayOrString // ErrNilValue is returned when value is nil. ErrNilValue = errors.New("nil value") // ErrNilConstValue is returned when trying to unmarshal into a nil ConstValue. ErrNilConstValue = errors.New("cannot unmarshal into nil ConstValue") // ErrIPv6AddressFormat is returned when an IPv6 address is not properly formatted. ErrIPv6AddressFormat = errors.New("ipv6 address format error") // Former: ErrIPv6AddressNotEnclosed // ErrInvalidIPv6 is returned when the IPv6 address is invalid. ErrInvalidIPv6 = errors.New("invalid ipv6 address") // Former: ErrInvalidIPv6Address )
=== Numeric and Format Related Errors ===
var ( // ErrAbsolutePathResolution is returned when absolute path resolution fails. ErrAbsolutePathResolution = errors.New("absolute path resolution failed") // Former: ErrFailedToResolveAbsolutePath // ErrCurrentDirectoryAccess is returned when getting current directory fails. ErrCurrentDirectoryAccess = errors.New("current directory access failed") // Former: ErrFailedToGetCurrentDirectory // ErrPathOutsideDirectory is returned when path is outside current directory. ErrPathOutsideDirectory = errors.New("path outside directory") // Former: ErrPathOutsideCurrentDirectory )
=== Path and Filesystem Related Errors ===
var ( // ErrFailedToReadData is deprecated: Use ErrDataRead instead ErrFailedToReadData = ErrDataRead // ErrFailedToFetch is deprecated: Use ErrNetworkFetch instead ErrFailedToFetch = ErrNetworkFetch // ErrInvalidHTTPStatusCode is deprecated: Use ErrInvalidStatusCode instead ErrInvalidHTTPStatusCode = ErrInvalidStatusCode // ErrFailedToWriteFile is deprecated: Use ErrFileWrite instead ErrFailedToWriteFile = ErrFileWrite // ErrFailedToCreateFile is deprecated: Use ErrFileCreation instead ErrFailedToCreateFile = ErrFileCreation // ErrFailedToCreateDirectory is deprecated: Use ErrDirectoryCreation instead ErrFailedToCreateDirectory = ErrDirectoryCreation // ErrFailedToWriteContent is deprecated: Use ErrContentWrite instead ErrFailedToWriteContent = ErrContentWrite // ErrJSONUnmarshalError is deprecated: Use ErrJSONUnmarshal instead ErrJSONUnmarshalError = ErrJSONUnmarshal // ErrXMLUnmarshalError is deprecated: Use ErrXMLUnmarshal instead ErrXMLUnmarshalError = ErrXMLUnmarshal // ErrYAMLUnmarshalError is deprecated: Use ErrYAMLUnmarshal instead ErrYAMLUnmarshalError = ErrYAMLUnmarshal // ErrFailedToDecodeJSON is deprecated: Use ErrJSONDecode instead ErrFailedToDecodeJSON = ErrJSONDecode // ErrFailedToEncodeSource is deprecated: Use ErrSourceEncode instead ErrFailedToEncodeSource = ErrSourceEncode // ErrFailedToDecodeIntermediateJSON is deprecated: Use ErrIntermediateJSONDecode instead ErrFailedToDecodeIntermediateJSON = ErrIntermediateJSONDecode // ErrFailedToEncodeData is deprecated: Use ErrDataEncode instead ErrFailedToEncodeData = ErrDataEncode // ErrFailedToEncodeNestedValue is deprecated: Use ErrNestedValueEncode instead ErrFailedToEncodeNestedValue = ErrNestedValueEncode // ErrFailedToCompileSchema is deprecated: Use ErrSchemaCompilation instead ErrFailedToCompileSchema = ErrSchemaCompilation // ErrFailedToResolveReference is deprecated: Use ErrReferenceResolution instead ErrFailedToResolveReference = ErrReferenceResolution // ErrFailedToResolveGlobalReference is deprecated: Use ErrGlobalReferenceResolution instead ErrFailedToResolveGlobalReference = ErrGlobalReferenceResolution // ErrFailedToResolveDefinitions is deprecated: Use ErrDefinitionResolution instead ErrFailedToResolveDefinitions = ErrDefinitionResolution // ErrFailedToResolveItems is deprecated: Use ErrItemResolution instead ErrFailedToResolveItems = ErrItemResolution // ErrFailedToDecodeSegmentWithJSONPointer is deprecated: Use ErrJSONPointerSegmentDecode instead ErrFailedToDecodeSegmentWithJSONPointer = ErrJSONPointerSegmentDecode // ErrSegmentNotFoundForJSONPointer is deprecated: Use ErrJSONPointerSegmentNotFound instead ErrSegmentNotFoundForJSONPointer = ErrJSONPointerSegmentNotFound // ErrInvalidJSONSchemaType is deprecated: Use ErrInvalidSchemaType instead ErrInvalidJSONSchemaType = ErrInvalidSchemaType // ErrTimeTypeConversion is deprecated: Use ErrTimeConversion instead ErrTimeTypeConversion = ErrTimeConversion // ErrTimeParseFailure is deprecated: Use ErrTimeParsing instead ErrTimeParseFailure = ErrTimeParsing // ErrFailedToConvertToRat is deprecated: Use ErrRatConversion instead ErrFailedToConvertToRat = ErrRatConversion // ErrCannotConvertSlice is deprecated: Use ErrSliceConversion instead ErrCannotConvertSlice = ErrSliceConversion // ErrCannotConvertSliceElement is deprecated: Use ErrSliceElementConversion instead ErrCannotConvertSliceElement = ErrSliceElementConversion // ErrCannotConvertFirstSlice is deprecated: Use ErrFirstSliceConversion instead ErrCannotConvertFirstSlice = ErrFirstSliceConversion // ErrCannotConvertSecondSlice is deprecated: Use ErrSecondSliceConversion instead ErrCannotConvertSecondSlice = ErrSecondSliceConversion // ErrCannotConvertNil is deprecated: Use ErrNilConversion instead ErrCannotConvertNil = ErrNilConversion // ErrCannotConvertNilPointer is deprecated: Use ErrNilPointerConversion instead ErrCannotConvertNilPointer = ErrNilPointerConversion // ErrCannotParseValue is deprecated: Use ErrValueParsing instead ErrCannotParseValue = ErrValueParsing // ErrCannotAssignValue is deprecated: Use ErrValueAssignment instead ErrCannotAssignValue = ErrValueAssignment // ErrUnsupportedTypeForRat is deprecated: Use ErrUnsupportedRatType instead ErrUnsupportedTypeForRat = ErrUnsupportedRatType // ErrUnsupportedTypeForGeneration is deprecated: Use ErrUnsupportedGenerationType instead ErrUnsupportedTypeForGeneration = ErrUnsupportedGenerationType // ErrInvalidTypeForTransform is deprecated: Use ErrInvalidTransformType instead ErrInvalidTypeForTransform = ErrInvalidTransformType // ErrFailedToParseStructTags is deprecated: Use ErrStructTagParse instead // ErrStructTagParsing is deprecated: Use ErrStructTagParsing instead ErrFailedToParseStructTags = ErrStructTagParsing // ErrFailedToSetField is deprecated: Use ErrFieldAssignment instead ErrFailedToSetField = ErrFieldAssignment // ErrFailedToAnalyzeFields is deprecated: Use ErrFieldAnalysis instead ErrFailedToAnalyzeFields = ErrFieldAnalysis // ErrFailedToApplyDefaults is deprecated: Use ErrDefaultApply instead // ErrDefaultApplication is deprecated: Use ErrDefaultApplication instead ErrFailedToApplyDefaults = ErrDefaultApplication // ErrFailedToEvaluateDefaultValue is deprecated: Use ErrDefaultEvaluation instead ErrFailedToEvaluateDefaultValue = ErrDefaultEvaluation // ErrFailedToApplyArrayDefaults is deprecated: Use ErrArrayDefaultApplication instead ErrFailedToApplyArrayDefaults = ErrArrayDefaultApplication // ErrFailedToParseFunctionCall is deprecated: Use ErrFunctionCallParsing instead ErrFailedToParseFunctionCall = ErrFunctionCallParsing // ErrConfigCannotBeNil is deprecated: Use ErrConfigNil instead // ErrNilConfig is deprecated: Use ErrNilConfig instead ErrConfigCannotBeNil = ErrNilConfig // ErrFailedToCreateAnalyzer is deprecated: Use ErrAnalyzerCreation instead ErrFailedToCreateAnalyzer = ErrAnalyzerCreation // ErrFailedToCreateWriter is deprecated: Use ErrWriterCreation instead ErrFailedToCreateWriter = ErrWriterCreation // ErrFailedToAnalyzePackage is deprecated: Use ErrPackageAnalysis instead ErrFailedToAnalyzePackage = ErrPackageAnalysis // ErrFailedToGenerateCode is deprecated: Use ErrCodeGeneration instead ErrFailedToGenerateCode = ErrCodeGeneration // ErrFailedToGenerateProperty is deprecated: Use ErrPropertyGeneration instead ErrFailedToGenerateProperty = ErrPropertyGeneration // ErrFailedToParseJSONSchemaTag is deprecated: Use ErrJSONSchemaTagParsing instead ErrFailedToParseJSONSchemaTag = ErrJSONSchemaTagParsing // ErrFailedToParseGozodTag is deprecated: Use ErrGozodTagParsing instead ErrFailedToParseGozodTag = ErrGozodTagParsing // ErrFailedToLoadTemplates is deprecated: Use ErrTemplateLoading instead ErrFailedToLoadTemplates = ErrTemplateLoading // ErrFailedToCreateOutputDirectory is deprecated: Use ErrOutputDirectoryCreation instead ErrFailedToCreateOutputDirectory = ErrOutputDirectoryCreation // ErrFailedToGenerateFieldSchemas is deprecated: Use ErrFieldSchemaGeneration instead ErrFailedToGenerateFieldSchemas = ErrFieldSchemaGeneration // ErrFailedToExecuteTemplate is deprecated: Use ErrTemplateExecution instead ErrFailedToExecuteTemplate = ErrTemplateExecution // ErrFailedToParseMainTemplate is deprecated: Use ErrMainTemplateParsing instead ErrFailedToParseMainTemplate = ErrMainTemplateParsing // ErrFailedToAnalyzeDependencies is deprecated: Use ErrDependencyAnalysis instead ErrFailedToAnalyzeDependencies = ErrDependencyAnalysis // ErrFailedToParseTemplate is deprecated: Use ErrTemplateParsing instead ErrFailedToParseTemplate = ErrTemplateParsing // ErrFailedToFormatCode is deprecated: Use ErrCodeFormatting instead ErrFailedToFormatCode = ErrCodeFormatting // ErrNegativeValue is deprecated: Use ErrValueNegative instead // ErrNegativeValueConversion is deprecated: Use ErrNegativeValueConversion instead ErrNegativeValue = ErrNegativeValueConversion // ErrNotWholeNumber is deprecated: Use ErrNonWholeNumber instead ErrNotWholeNumber = ErrNonWholeNumber // ErrNotSliceArrayOrString is deprecated: Use ErrInvalidSliceArrayString instead ErrNotSliceArrayOrString = ErrInvalidSliceArrayString // ErrIPv6AddressNotEnclosed is deprecated: Use ErrIPv6AddressFormat instead ErrIPv6AddressNotEnclosed = ErrIPv6AddressFormat // ErrInvalidIPv6Address is deprecated: Use ErrInvalidIPv6 instead ErrInvalidIPv6Address = ErrInvalidIPv6 // ErrFailedToResolveAbsolutePath is deprecated: Use ErrPathResolve instead // ErrAbsolutePathResolution is deprecated: Use ErrAbsolutePathResolution instead ErrFailedToResolveAbsolutePath = ErrAbsolutePathResolution // ErrFailedToGetCurrentDirectory is deprecated: Use ErrCurrentDirectoryAccess instead ErrFailedToGetCurrentDirectory = ErrCurrentDirectoryAccess // ErrPathOutsideCurrentDirectory is deprecated: Use ErrPathOutsideDirectory instead ErrPathOutsideCurrentDirectory = ErrPathOutsideDirectory )
var ( // ErrUnderlyingError is returned as a generic underlying error. ErrUnderlyingError = errors.New("underlying error") // To be deprecated: insufficient information )
=== Legacy and Generic Errors (To be gradually deprecated) ===
var Formats = map[string]func(any) bool{ "date-time": IsDateTime, "date": IsDate, "time": IsTime, "duration": IsDuration, "period": IsPeriod, "hostname": IsHostname, "email": IsEmail, "ip-address": IsIPV4, "ipv4": IsIPV4, "ipv6": IsIPV6, "uri": IsURI, "iri": IsURI, "uri-reference": IsURIReference, "uriref": IsURIReference, "iri-reference": IsURIReference, "uri-template": IsURITemplate, "json-pointer": IsJSONPointer, "relative-json-pointer": IsRelativeJSONPointer, "uuid": IsUUID, "regex": IsRegex, "unknown": func(any) bool { return true }, }
Formats is a registry of functions, which know how to validate a specific format.
New Formats can be registered by adding to this map. Key is format name, value is function that knows how to validate that format.
Functions ¶
func CacheStats ¶ added in v0.6.11
CacheStats returns statistics about the global schema cache - useful for monitoring
func ClearSchemaCache ¶ added in v0.4.7
func ClearSchemaCache()
ClearSchemaCache clears the global schema cache - useful for testing and memory management
func DefaultNowFunc ¶ added in v0.4.1
DefaultNowFunc generates current timestamp in various formats This function must be manually registered by developers
func I18n ¶ added in v0.6.11
I18n returns an initialized internationalization bundle with embedded locales
func IsDate ¶
IsDate tells whether given string is a valid full-date production as defined by RFC 3339, section 5.6.
see https://datatracker.ietf.org/doc/html/rfc3339#section-5.6, for details
func IsDateTime ¶
IsDateTime tells whether given string is a valid date representation as defined by RFC 3339, section 5.6.
see https://datatracker.ietf.org/doc/html/rfc3339#section-5.6, for details
func IsDuration ¶
IsDuration tells whether given string is a valid duration format from the ISO 8601 ABNF as given in Appendix A of RFC 3339.
see https://datatracker.ietf.org/doc/html/rfc3339#appendix-A, for details
func IsEmail ¶
IsEmail tells whether given string is a valid Internet email address as defined by RFC 5322, section 3.4.1.
See https://en.wikipedia.org/wiki/Email_address, for details.
func IsHostname ¶
IsHostname tells whether given string is a valid representation for an Internet host name, as defined by RFC 1034 section 3.1 and RFC 1123 section 2.1.
See https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names, for details.
func IsIPV4 ¶
IsIPV4 tells whether given string is a valid representation of an IPv4 address according to the "dotted-quad" ABNF syntax as defined in RFC 2673, section 3.2.
func IsIPV6 ¶
IsIPV6 tells whether given string is a valid representation of an IPv6 address as defined in RFC 2373, section 2.2.
func IsJSONPointer ¶
IsJSONPointer tells whether given string is a valid JSON Pointer.
Note: It returns false for JSON Pointer URI fragments.
func IsPeriod ¶
IsPeriod tells whether given string is a valid period format from the ISO 8601 ABNF as given in Appendix A of RFC 3339.
see https://datatracker.ietf.org/doc/html/rfc3339#appendix-A, for details
func IsRelativeJSONPointer ¶
IsRelativeJSONPointer tells whether given string is a valid Relative JSON Pointer.
see https://tools.ietf.org/html/draft-handrews-relative-json-pointer-01#section-3
func IsTime ¶
IsTime tells whether given string is a valid full-time production as defined by RFC 3339, section 5.6.
see https://datatracker.ietf.org/doc/html/rfc3339#section-5.6, for details
func IsURIReference ¶
IsURIReference tells whether given string is a valid URI Reference (either a URI or a relative-reference), according to RFC 3986.
func IsURITemplate ¶
IsURITemplate tells whether given string is a valid URI Template according to RFC6570.
Current implementation does minimal validation.
func IsUUID ¶
IsUUID tells whether given string is a valid uuid format as specified in RFC4122.
see https://datatracker.ietf.org/doc/html/rfc4122#page-4, for details
func RegisterCustomValidator ¶ added in v0.4.7
func RegisterCustomValidator(name string, validator CustomValidatorFunc)
RegisterCustomValidator registers a custom validator globally
func SetDefaultCompiler ¶ added in v0.4.1
func SetDefaultCompiler(c *Compiler)
SetDefaultCompiler allows setting a custom compiler for the constructor API
Types ¶
type Compiler ¶
type Compiler struct {
Decoders map[string]func(string) ([]byte, error) // Decoders for various encoding formats.
MediaTypes map[string]func([]byte) (any, error) // Media type handlers for unmarshalling data.
Loaders map[string]func(url string) (io.ReadCloser, error) // Functions to load schemas from URLs.
DefaultBaseURI string // Base URI used to resolve relative references.
AssertFormat bool // Flag to enforce format validation.
// PreserveExtra indicates whether to preserve unknown keywords in the schema.
// If false (default), unknown keywords are stripped during compilation.
PreserveExtra bool
// contains filtered or unexported fields
}
Compiler represents a JSON Schema compiler that manages schema compilation and caching.
func DefaultCompiler ¶ added in v0.6.11
func DefaultCompiler() *Compiler
DefaultCompiler returns the current default compiler
func NewCompiler ¶
func NewCompiler() *Compiler
NewCompiler creates a new Compiler instance and initializes it with default settings.
func (*Compiler) Compile ¶
Compile compiles a JSON schema and caches it. If an URI is provided, it uses that as the key; otherwise, it generates a hash.
func (*Compiler) CompileBatch ¶ added in v0.4.2
CompileBatch compiles multiple schemas efficiently by deferring reference resolution until all schemas are compiled. This is the most efficient approach when you have many schemas with interdependencies.
func (*Compiler) RegisterDecoder ¶
func (c *Compiler) RegisterDecoder(encodingName string, decoderFunc func(string) ([]byte, error)) *Compiler
RegisterDecoder adds a new decoder function for a specific encoding.
func (*Compiler) RegisterDefaultFunc ¶ added in v0.4.1
func (c *Compiler) RegisterDefaultFunc(name string, fn DefaultFunc) *Compiler
RegisterDefaultFunc registers a function for dynamic default value generation.
func (*Compiler) RegisterFormat ¶ added in v0.4.5
func (c *Compiler) RegisterFormat(name string, validator func(any) bool, typeName ...string) *Compiler
RegisterFormat registers a custom format. The optional typeName parameter specifies which JSON Schema type the format applies to. (e.g., "string", "number"). If omitted, the format applies to all types.
func (*Compiler) RegisterLoader ¶
func (c *Compiler) RegisterLoader(scheme string, loaderFunc func(url string) (io.ReadCloser, error)) *Compiler
RegisterLoader adds a new loader function for a specific URI scheme.
func (*Compiler) RegisterMediaType ¶
func (c *Compiler) RegisterMediaType(mediaTypeName string, unmarshalFunc func([]byte) (any, error)) *Compiler
RegisterMediaType adds a new unmarshal function for a specific media type.
func (*Compiler) Schema ¶ added in v0.6.11
Schema retrieves a schema by reference. If the schema is not found in the cache and the ref is a URL, it tries to resolve it.
func (*Compiler) SetAssertFormat ¶
SetAssertFormat enables or disables format assertion.
func (*Compiler) SetDefaultBaseURI ¶
SetDefaultBaseURI sets the default base URL for resolving relative references.
func (*Compiler) SetPreserveExtra ¶ added in v0.6.8
SetPreserveExtra sets whether to preserve unknown keywords in the schema.
func (*Compiler) UnregisterFormat ¶ added in v0.4.5
UnregisterFormat removes a custom format.
func (*Compiler) WithDecoderJSON ¶ added in v0.2.3
WithDecoderJSON configures custom JSON decoder implementation.
type ConditionalSchema ¶ added in v0.4.0
type ConditionalSchema struct {
// contains filtered or unexported fields
}
ConditionalSchema represents a conditional schema for if/then/else logic
func If ¶ added in v0.4.0
func If(condition *Schema) *ConditionalSchema
If creates a conditional Schema with if/then/else keywords
func (*ConditionalSchema) Else ¶ added in v0.4.0
func (cs *ConditionalSchema) Else(otherwise *Schema) *Schema
Else sets the else clause of a conditional schema
func (*ConditionalSchema) Then ¶ added in v0.4.0
func (cs *ConditionalSchema) Then(then *Schema) *ConditionalSchema
Then sets the then clause of a conditional schema
func (*ConditionalSchema) ToSchema ¶ added in v0.4.0
func (cs *ConditionalSchema) ToSchema() *Schema
ToSchema converts a conditional schema to a regular schema
type ConstValue ¶
ConstValue represents a constant value in a JSON Schema.
func (ConstValue) MarshalJSON ¶
func (cv ConstValue) MarshalJSON() ([]byte, error)
MarshalJSON handles marshaling the ConstValue type back to JSON.
func (*ConstValue) UnmarshalJSON ¶
func (cv *ConstValue) UnmarshalJSON(data []byte) error
UnmarshalJSON handles unmarshaling a JSON value into the ConstValue type.
type CustomValidatorFunc ¶ added in v0.4.7
CustomValidatorFunc represents a custom validator function
type DefaultFunc ¶ added in v0.4.1
DefaultFunc represents a function that can generate dynamic default values.
type DynamicScope ¶
type DynamicScope struct {
// contains filtered or unexported fields
}
DynamicScope struct defines a stack specifically for handling Schema types.
func NewDynamicScope ¶
func NewDynamicScope() *DynamicScope
NewDynamicScope creates and returns a new empty DynamicScope.
func (*DynamicScope) Contains ¶ added in v0.4.14
func (ds *DynamicScope) Contains(schema *Schema) bool
Contains checks if a schema is already in the dynamic scope (circular reference detection).
func (*DynamicScope) IsEmpty ¶
func (ds *DynamicScope) IsEmpty() bool
IsEmpty checks if the dynamic scope is empty.
func (*DynamicScope) LookupDynamicAnchor ¶
func (ds *DynamicScope) LookupDynamicAnchor(anchor string) *Schema
LookupDynamicAnchor searches for a dynamic anchor in the dynamic scope.
func (*DynamicScope) Peek ¶
func (ds *DynamicScope) Peek() *Schema
Peek returns the top Schema without removing it.
func (*DynamicScope) Pop ¶
func (ds *DynamicScope) Pop() *Schema
Pop removes and returns the top Schema from the dynamic scope.
func (*DynamicScope) Push ¶
func (ds *DynamicScope) Push(schema *Schema)
Push adds a Schema to the dynamic scope.
func (*DynamicScope) Size ¶
func (ds *DynamicScope) Size() int
Size returns the number of Schemas in the dynamic scope.
type EvaluationError ¶
type EvaluationError struct {
Keyword string `json:"keyword"`
Code string `json:"code"`
Message string `json:"message"`
Params map[string]any `json:"params"`
}
EvaluationError represents an error that occurred during schema evaluation
func NewEvaluationError ¶
func NewEvaluationError(keyword string, code string, message string, params ...map[string]any) *EvaluationError
NewEvaluationError creates a new evaluation error with the specified details
func (*EvaluationError) Error ¶
func (e *EvaluationError) Error() string
Error returns a string representation of the evaluation error.
type EvaluationResult ¶
type EvaluationResult struct {
Valid bool `json:"valid"`
EvaluationPath string `json:"evaluationPath"`
SchemaLocation string `json:"schemaLocation"`
InstanceLocation string `json:"instanceLocation"`
Annotations map[string]any `json:"annotations,omitempty"`
Errors map[string]*EvaluationError `json:"errors,omitempty"` // Store error messages here
Details []*EvaluationResult `json:"details,omitempty"`
// contains filtered or unexported fields
}
EvaluationResult represents the complete result of a schema validation
func NewEvaluationResult ¶
func NewEvaluationResult(schema *Schema) *EvaluationResult
NewEvaluationResult creates a new evaluation result for the given schema
func (*EvaluationResult) AddAnnotation ¶
func (e *EvaluationResult) AddAnnotation(keyword string, annotation any) *EvaluationResult
AddAnnotation adds an annotation to this result
func (*EvaluationResult) AddDetail ¶
func (e *EvaluationResult) AddDetail(detail *EvaluationResult) *EvaluationResult
AddDetail adds a detailed evaluation result to this result
func (*EvaluationResult) AddError ¶
func (e *EvaluationResult) AddError(err *EvaluationError) *EvaluationResult
AddError adds an evaluation error to this result
func (*EvaluationResult) CollectAnnotations ¶
func (e *EvaluationResult) CollectAnnotations() *EvaluationResult
CollectAnnotations collects annotations from child results
func (*EvaluationResult) DetailedErrors ¶ added in v0.6.11
func (e *EvaluationResult) DetailedErrors(localizer ...*i18n.Localizer) map[string]string
DetailedErrors collects all detailed validation errors from the nested Details hierarchy. This method helps users access specific validation failures that might be buried in nested structures. Returns a map where keys are field paths and values are the most specific error messages. For localized messages, pass a localizer; for default English messages, call without arguments.
func (*EvaluationResult) Error ¶ added in v0.2.2
func (e *EvaluationResult) Error() string
Error returns a string representation of the evaluation failure.
func (*EvaluationResult) IsValid ¶
func (e *EvaluationResult) IsValid() bool
IsValid returns whether this result is valid
func (*EvaluationResult) SetEvaluationPath ¶
func (e *EvaluationResult) SetEvaluationPath(evaluationPath string) *EvaluationResult
SetEvaluationPath sets the evaluation path for this result
func (*EvaluationResult) SetInstanceLocation ¶
func (e *EvaluationResult) SetInstanceLocation(instanceLocation string) *EvaluationResult
SetInstanceLocation sets the instance location for this result
func (*EvaluationResult) SetInvalid ¶
func (e *EvaluationResult) SetInvalid() *EvaluationResult
SetInvalid marks this result as invalid
func (*EvaluationResult) SetSchemaLocation ¶
func (e *EvaluationResult) SetSchemaLocation(location string) *EvaluationResult
SetSchemaLocation sets the schema location for this result
func (*EvaluationResult) ToFlag ¶
func (e *EvaluationResult) ToFlag() *Flag
ToFlag converts EvaluationResult to a simple Flag struct
func (*EvaluationResult) ToList ¶
func (e *EvaluationResult) ToList(includeHierarchy ...bool) *List
ToList converts the evaluation results into a list format with optional hierarchy includeHierarchy is variadic; if not provided, it defaults to true
func (*EvaluationResult) ToLocalizeList ¶
func (e *EvaluationResult) ToLocalizeList(localizer *i18n.Localizer, includeHierarchy ...bool) *List
ToLocalizeList converts the evaluation results into a list format with optional hierarchy with localization. includeHierarchy is variadic; if not provided, it defaults to true
type FieldCache ¶ added in v0.2.5
FieldCache stores parsed field information for a struct type
type FieldInfo ¶ added in v0.2.5
type FieldInfo struct {
Index int // Field index in the struct
JSONName string // JSON field name (after processing tags)
Omitempty bool // Whether the field has omitempty tag
Omitzero bool // Whether the field has omitzero tag
Type reflect.Type // Field type
}
FieldInfo contains metadata for a struct field
type Flag ¶
type Flag struct {
Valid bool `json:"valid"`
}
Flag represents a simple validation result with just validity status
type FormatDef ¶ added in v0.4.5
type FormatDef struct {
// Type specifies which JSON Schema type this format applies to (optional)
// Supported values: "string", "number", "integer", "boolean", "array", "object"
// Empty string means applies to all types
Type string
// Validate is the validation function
Validate func(any) bool
}
FormatDef defines a custom format validation rule.
type FunctionCall ¶ added in v0.4.1
FunctionCall represents a parsed function call with name and arguments
type Keyword ¶ added in v0.4.0
type Keyword func(*Schema)
Keyword represents a schema keyword that can be applied to any schema
func AdditionalProps ¶ added in v0.4.0
AdditionalProps sets the additionalProperties keyword
func AdditionalPropsSchema ¶ added in v0.4.0
AdditionalPropsSchema sets the additionalProperties keyword with a schema
func ContentEncoding ¶ added in v0.4.0
ContentEncoding sets the contentEncoding keyword
func ContentMediaType ¶ added in v0.4.0
ContentMediaType sets the contentMediaType keyword
func ContentSchema ¶ added in v0.4.0
ContentSchema sets the contentSchema keyword
func DependentRequired ¶ added in v0.4.0
DependentRequired sets the dependentRequired keyword
func DependentSchemas ¶ added in v0.4.0
DependentSchemas sets the dependentSchemas keyword
func Deprecated ¶ added in v0.4.0
Deprecated sets the deprecated keyword
func Description ¶ added in v0.4.0
Description sets the description keyword
func DynamicAnchor ¶ added in v0.4.0
DynamicAnchor sets the $dynamicAnchor keyword
func ExclusiveMax ¶ added in v0.4.0
ExclusiveMax sets the exclusiveMaximum keyword
func ExclusiveMin ¶ added in v0.4.0
ExclusiveMin sets the exclusiveMinimum keyword
func MaxContains ¶ added in v0.4.0
MaxContains sets the maxContains keyword
func MinContains ¶ added in v0.4.0
MinContains sets the minContains keyword
func MultipleOf ¶ added in v0.4.0
MultipleOf sets the multipleOf keyword
func PatternProps ¶ added in v0.4.0
PatternProps sets the patternProperties keyword
func PrefixItems ¶ added in v0.4.0
PrefixItems sets the prefixItems keyword
func PropertyNames ¶ added in v0.4.0
PropertyNames sets the propertyNames keyword
func UnevaluatedItems ¶ added in v0.4.0
UnevaluatedItems sets the unevaluatedItems keyword
func UnevaluatedProps ¶ added in v0.4.0
UnevaluatedProps sets the unevaluatedProperties keyword
func UniqueItems ¶ added in v0.4.0
UniqueItems sets the uniqueItems keyword
type List ¶
type List struct {
Valid bool `json:"valid"`
EvaluationPath string `json:"evaluationPath"`
SchemaLocation string `json:"schemaLocation"`
InstanceLocation string `json:"instanceLocation"`
Annotations map[string]any `json:"annotations,omitempty"`
Errors map[string]string `json:"errors,omitempty"`
Details []List `json:"details,omitempty"`
}
List represents a flat list of validation errors
type Rat ¶
Rat wraps a big.Rat to enable custom JSON marshaling and unmarshaling.
func (*Rat) MarshalJSON ¶
MarshalJSON implements the json.Marshaler interface for Rat.
func (*Rat) UnmarshalJSON ¶
UnmarshalJSON implements the json.Unmarshaler interface for Rat.
type RegexPatternError ¶ added in v0.6.0
type RegexPatternError struct {
// Keyword identifies the JSON Schema keyword containing the invalid pattern.
// Examples: "pattern", "patternProperties".
Keyword string
// Location is the JSON Pointer path to the keyword instance.
// Example: "#/properties/email/pattern".
Location string
// Pattern is the regex pattern that failed to compile.
Pattern string
// Err is the underlying regexp compilation error.
Err error
}
RegexPatternError provides structured context for invalid regular expressions discovered during schema compilation.
func (*RegexPatternError) Error ¶ added in v0.6.0
func (e *RegexPatternError) Error() string
Error returns a formatted error message with full context.
func (*RegexPatternError) Unwrap ¶ added in v0.6.0
func (e *RegexPatternError) Unwrap() error
Unwrap returns the compilation error for compatibility with errors.Is/As.
type RequiredSort ¶ added in v0.5.1
type RequiredSort string
RequiredSort controls how required field names are ordered
const ( // RequiredSortAlphabetical sorts required fields alphabetically for deterministic output RequiredSortAlphabetical RequiredSort = "alphabetical" // RequiredSortNone does not sort required fields, preserving the order from struct field iteration // Note: May be non-deterministic due to map iteration in TagParser RequiredSortNone RequiredSort = "none" )
type Schema ¶
type Schema struct {
ID string `json:"$id,omitempty"` // Public identifier for the schema.
Schema string `json:"$schema,omitempty"` // URI indicating the specification the schema conforms to.
Format *string `json:"format,omitempty"` // Format hint for string data, e.g., "email" or "date-time".
// Schema reference keywords, see https://json-schema.org/draft/2020-12/json-schema-core#ref
Ref string `json:"$ref,omitempty"` // Reference to another schema.
DynamicRef string `json:"$dynamicRef,omitempty"` // Reference to another schema that can be dynamically resolved.
Anchor string `json:"$anchor,omitempty"` // Anchor for resolving relative JSON Pointers.
DynamicAnchor string `json:"$dynamicAnchor,omitempty"` // Anchor for dynamic resolution
Defs map[string]*Schema `json:"$defs,omitempty"` // An object containing schema definitions.
ResolvedRef *Schema `json:"-"` // Resolved schema for $ref
ResolvedDynamicRef *Schema `json:"-"` // Resolved schema for $dynamicRef
// Boolean JSON Schemas, see https://json-schema.org/draft/2020-12/json-schema-core#name-boolean-json-schemas
Boolean *bool `json:"-"` // Boolean schema, used for quick validation.
// Applying subschemas with logical keywords, see https://json-schema.org/draft/2020-12/json-schema-core#name-keywords-for-applying-subsch
AllOf []*Schema `json:"allOf,omitempty"` // Array of schemas for validating the instance against all of them.
AnyOf []*Schema `json:"anyOf,omitempty"` // Array of schemas for validating the instance against any of them.
OneOf []*Schema `json:"oneOf,omitempty"` // Array of schemas for validating the instance against exactly one of them.
Not *Schema `json:"not,omitempty"` // Schema for validating the instance against the negation of it.
// Applying subschemas conditionally, see https://json-schema.org/draft/2020-12/json-schema-core#name-keywords-for-applying-subsche
If *Schema `json:"if,omitempty"` // Schema to be evaluated as a condition
Then *Schema `json:"then,omitempty"` // Schema to be evaluated if 'if' is successful
Else *Schema `json:"else,omitempty"` // Schema to be evaluated if 'if' is not successful
DependentSchemas map[string]*Schema `json:"dependentSchemas,omitempty"` // Dependent schemas based on property presence
// Applying subschemas to array keywords, see https://json-schema.org/draft/2020-12/json-schema-core#name-keywords-for-applying-subschem
PrefixItems []*Schema `json:"prefixItems,omitempty"` // Array of schemas for validating the array items' prefix.
Items *Schema `json:"items,omitempty"` // Schema for items in an array.
Contains *Schema `json:"contains,omitempty"` // Schema for validating items in the array.
// Applying subschemas to objects keywords, see https://json-schema.org/draft/2020-12/json-schema-core#name-keywords-for-applying-subschemas
Properties *SchemaMap `json:"properties,omitempty"` // Definitions of properties for object types.
PatternProperties *SchemaMap `json:"patternProperties,omitempty"` // Definitions of properties for object types matched by specific patterns.
AdditionalProperties *Schema `json:"additionalProperties,omitempty"` // Can be a boolean or a schema, controls additional properties handling.
PropertyNames *Schema `json:"propertyNames,omitempty"` // Can be a boolean or a schema, controls property names validation.
// Any validation keywords, see https://json-schema.org/draft/2020-12/json-schema-validation#section-6.1
Type SchemaType `json:"type,omitempty"` // Can be a single type or an array of types.
Enum []any `json:"enum,omitempty"` // Enumerated values for the property.
Const *ConstValue `json:"const,omitempty"` // Constant value for the property.
// Numeric validation keywords, see https://json-schema.org/draft/2020-12/json-schema-validation#section-6.2
MultipleOf *Rat `json:"multipleOf,omitempty"` // Number must be a multiple of this value, strictly greater than 0.
Maximum *Rat `json:"maximum,omitempty"` // Maximum value of the number.
ExclusiveMaximum *Rat `json:"exclusiveMaximum,omitempty"` // Number must be less than this value.
Minimum *Rat `json:"minimum,omitempty"` // Minimum value of the number.
ExclusiveMinimum *Rat `json:"exclusiveMinimum,omitempty"` // Number must be greater than this value.
// String validation keywords, see https://json-schema.org/draft/2020-12/json-schema-validation#section-6.3
MaxLength *float64 `json:"maxLength,omitempty"` // Maximum length of a string.
MinLength *float64 `json:"minLength,omitempty"` // Minimum length of a string.
Pattern *string `json:"pattern,omitempty"` // Regular expression pattern to match the string against.
// Array validation keywords, see https://json-schema.org/draft/2020-12/json-schema-validation#section-6.4
MaxItems *float64 `json:"maxItems,omitempty"` // Maximum number of items in an array.
MinItems *float64 `json:"minItems,omitempty"` // Minimum number of items in an array.
UniqueItems *bool `json:"uniqueItems,omitempty"` // Whether the items in the array must be unique.
MaxContains *float64 `json:"maxContains,omitempty"` // Maximum number of items in the array that can match the contains schema.
MinContains *float64 `json:"minContains,omitempty"` // Minimum number of items in the array that must match the contains schema.
// https://json-schema.org/draft/2020-12/json-schema-core#name-unevaluateditems
UnevaluatedItems *Schema `json:"unevaluatedItems,omitempty"` // Schema for unevaluated items in an array.
// Object validation keywords, see https://json-schema.org/draft/2020-12/json-schema-validation#section-6.5
MaxProperties *float64 `json:"maxProperties,omitempty"` // Maximum number of properties in an object.
MinProperties *float64 `json:"minProperties,omitempty"` // Minimum number of properties in an object.
Required []string `json:"required,omitempty"` // List of required property names for object types.
DependentRequired map[string][]string `json:"dependentRequired,omitempty"` // Properties required when another property is present.
// https://json-schema.org/draft/2020-12/json-schema-core#name-unevaluatedproperties
UnevaluatedProperties *Schema `json:"unevaluatedProperties,omitempty"` // Schema for unevaluated properties in an object.
// Content validation keywords, see https://json-schema.org/draft/2020-12/json-schema-validation#name-a-vocabulary-for-the-conten
ContentEncoding *string `json:"contentEncoding,omitempty"` // Encoding format of the content.
ContentMediaType *string `json:"contentMediaType,omitempty"` // Media type of the content.
ContentSchema *Schema `json:"contentSchema,omitempty"` // Schema for validating the content.
// Meta-data for schema and instance description, see https://json-schema.org/draft/2020-12/json-schema-validation#name-a-vocabulary-for-basic-meta
Title *string `json:"title,omitempty"` // A short summary of the schema.
Description *string `json:"description,omitempty"` // A detailed description of the purpose of the schema.
Default any `json:"default,omitempty"` // Default value of the instance.
Deprecated *bool `json:"deprecated,omitempty"` // Indicates that the schema is deprecated.
ReadOnly *bool `json:"readOnly,omitempty"` // Indicates that the property is read-only.
WriteOnly *bool `json:"writeOnly,omitempty"` // Indicates that the property is write-only.
Examples []any `json:"examples,omitempty"` // Examples of the instance data that validates against this schema.
// Extra keywords not in specification
Extra map[string]any `json:"-"`
// contains filtered or unexported fields
}
Schema represents a JSON Schema as per the 2020-12 draft, containing all necessary metadata and validation properties defined by the specification.
func DateTime ¶ added in v0.4.0
func DateTime() *Schema
DateTime creates a date-time format string schema
func Duration ¶ added in v0.4.0
func Duration() *Schema
Duration creates a duration format string schema
func FromStruct ¶ added in v0.4.7
FromStruct generates a JSON Schema from a struct type with jsonschema tags.
func FromStructWithOptions ¶ added in v0.4.7
func FromStructWithOptions[T any](options *StructTagOptions) (*Schema, error)
FromStructWithOptions generates a JSON Schema from a struct type with custom options.
func Hostname ¶ added in v0.4.0
func Hostname() *Schema
Hostname creates a hostname format string schema
func IRIRef ¶ added in v0.4.0
func IRIRef() *Schema
IRIRef creates an IRI reference format string schema
func IdnEmail ¶ added in v0.4.0
func IdnEmail() *Schema
IdnEmail creates an internationalized email format string schema
func IdnHostname ¶ added in v0.4.0
func IdnHostname() *Schema
IdnHostname creates an internationalized hostname format string schema
func JSONPointer ¶ added in v0.4.0
func JSONPointer() *Schema
JSONPointer creates a JSON pointer format string schema
func NegativeInt ¶ added in v0.4.0
func NegativeInt() *Schema
NegativeInt creates a negative integer schema
func NonNegativeInt ¶ added in v0.4.0
func NonNegativeInt() *Schema
NonNegativeInt creates a non-negative integer schema
func NonPositiveInt ¶ added in v0.4.0
func NonPositiveInt() *Schema
NonPositiveInt creates a non-positive integer schema
func PositiveInt ¶ added in v0.4.0
func PositiveInt() *Schema
PositiveInt creates a positive integer schema
func RelativeJSONPointer ¶ added in v0.4.0
func RelativeJSONPointer() *Schema
RelativeJSONPointer creates a relative JSON pointer format string schema
func URIRef ¶ added in v0.4.0
func URIRef() *Schema
URIRef creates a URI reference format string schema
func URITemplate ¶ added in v0.4.0
func URITemplate() *Schema
URITemplate creates a URI template format string schema
func (*Schema) Compiler ¶ added in v0.6.11
Compiler gets the effective Compiler for the Schema Lookup order: current Schema -> parent Schema -> defaultCompiler
func (*Schema) MarshalJSON ¶
MarshalJSON implements json.Marshaler
func (*Schema) MarshalJSONTo ¶ added in v0.4.14
MarshalJSONTo implements json.MarshalerTo for JSON v2 with proper option support
func (*Schema) ResolveUnresolvedReferences ¶ added in v0.4.2
func (s *Schema) ResolveUnresolvedReferences()
ResolveUnresolvedReferences tries to resolve any previously unresolved references. This is called after new schemas are added to the compiler.
func (*Schema) SchemaLocation ¶ added in v0.6.11
SchemaLocation returns the schema location with the given anchor
func (*Schema) SchemaURI ¶ added in v0.6.11
SchemaURI returns the resolved URI for the schema, or an empty string if no URI is defined.
func (*Schema) SetCompiler ¶ added in v0.4.1
SetCompiler sets a custom Compiler for the Schema and returns the Schema itself to support method chaining
func (*Schema) Unmarshal ¶ added in v0.2.6
Unmarshal unmarshals data into dst, applying default values from the schema. This method does NOT perform validation - use Validate() separately for validation.
Supported source types:
- []byte (JSON data - automatically parsed if valid JSON)
- map[string]any (parsed JSON object)
- Go structs and other types
Supported destination types:
- *struct (Go struct pointer)
- *map[string]any (map pointer)
- other pointer types (via JSON marshaling)
Example usage:
result := schema.Validate(data)
if result.IsValid() {
err := schema.Unmarshal(&user, data)
if err != nil {
log.Fatal(err)
}
} else {
// Handle validation errors
for field, err := range result.Errors {
log.Printf("%s: %s", field, err.Message)
}
}
To use JSON strings, convert them to []byte first:
schema.Unmarshal(&target, []byte(jsonString))
func (*Schema) UnmarshalJSON ¶
UnmarshalJSON handles unmarshaling JSON data into the Schema type.
func (*Schema) UnresolvedReferenceURIs ¶ added in v0.6.11
UnresolvedReferenceURIs returns a list of URIs that this schema references but are not yet resolved.
func (*Schema) Validate ¶
func (s *Schema) Validate(instance any) *EvaluationResult
Validate checks if the given instance conforms to the schema. This method automatically detects the input type and delegates to the appropriate validation method.
func (*Schema) ValidateJSON ¶ added in v0.3.0
func (s *Schema) ValidateJSON(data []byte) *EvaluationResult
ValidateJSON validates JSON data provided as []byte. The input is guaranteed to be treated as JSON data and parsed accordingly.
func (*Schema) ValidateMap ¶ added in v0.3.0
func (s *Schema) ValidateMap(data map[string]any) *EvaluationResult
ValidateMap validates map[string]any data directly. This method provides optimal performance for pre-parsed JSON data.
func (*Schema) ValidateStruct ¶ added in v0.3.0
func (s *Schema) ValidateStruct(instance any) *EvaluationResult
ValidateStruct validates Go struct data directly using reflection. This method uses cached reflection data for optimal performance.
type SchemaMap ¶
SchemaMap represents a map of string keys to *Schema values, used primarily for properties and patternProperties.
func (SchemaMap) MarshalJSON ¶
MarshalJSON ensures that SchemaMap serializes properly as a JSON object.
func (*SchemaMap) MarshalJSONTo ¶ added in v0.4.14
MarshalJSONTo implements json.MarshalerTo for JSON v2 with proper option support
func (*SchemaMap) UnmarshalJSON ¶
UnmarshalJSON ensures that JSON objects are correctly parsed into SchemaMap, supporting the detailed structure required for nested schema definitions.
type SchemaType ¶ added in v0.2.0
type SchemaType []string
SchemaType holds a set of SchemaType values, accommodating complex schema definitions that permit multiple types.
func (SchemaType) MarshalJSON ¶ added in v0.2.0
func (st SchemaType) MarshalJSON() ([]byte, error)
MarshalJSON customizes the JSON serialization of SchemaType.
func (*SchemaType) UnmarshalJSON ¶ added in v0.2.0
func (st *SchemaType) UnmarshalJSON(data []byte) error
UnmarshalJSON customizes the JSON deserialization into SchemaType.
type StructTagError ¶ added in v0.4.7
type StructTagError struct {
StructType string // The type name of the struct being processed
FieldName string // The name of the field with the error
TagRule string // The tag rule that failed (e.g., "pattern=...")
Message string // Human-readable error message
Err error // Underlying error (renamed from Cause for consistency with UnmarshalError)
}
StructTagError represents an error that occurred during struct tag processing. It provides detailed context about which struct, field, and tag rule caused the error.
func (*StructTagError) Error ¶ added in v0.4.7
func (e *StructTagError) Error() string
Error returns a formatted error message with full context.
func (*StructTagError) Unwrap ¶ added in v0.4.7
func (e *StructTagError) Unwrap() error
Unwrap returns the underlying error, allowing error chain inspection with errors.Is/As.
type StructTagOptions ¶ added in v0.4.7
type StructTagOptions struct {
TagName string // tag name to parse (default: "jsonschema")
AllowUntaggedFields bool // whether to include fields without tags (default: false)
DefaultRequired bool // whether fields are required by default (default: false)
FieldNameMapper func(string) string // function to map Go field names to JSON names
CustomValidators map[string]any // custom validators (for future extension)
CacheEnabled bool // whether to enable schema caching (default: true)
SchemaVersion string // $schema URI to include in generated schemas (empty string = omit $schema, default = Draft 2020-12)
RequiredSort RequiredSort // controls ordering of required fields (default: RequiredSortAlphabetical)
// Schema-level properties using map approach
SchemaProperties map[string]any // flexible configuration for any schema property
}
StructTagOptions holds configuration for struct tag schema generation
func DefaultStructTagOptions ¶ added in v0.4.7
func DefaultStructTagOptions() *StructTagOptions
DefaultStructTagOptions returns the default configuration for struct tag processing
type UnmarshalError ¶ added in v0.2.6
UnmarshalError represents an error that occurred during unmarshaling
func (*UnmarshalError) Error ¶ added in v0.2.6
func (e *UnmarshalError) Error() string
Error returns a string representation of the unmarshal error.
func (*UnmarshalError) Unwrap ¶ added in v0.2.6
func (e *UnmarshalError) Unwrap() error
Unwrap returns the underlying error.
type ValidatorRegistry ¶ added in v0.4.7
type ValidatorRegistry struct {
// contains filtered or unexported fields
}
ValidatorRegistry manages custom validators
func (*ValidatorRegistry) CustomValidator ¶ added in v0.6.11
func (r *ValidatorRegistry) CustomValidator(name string) (CustomValidatorFunc, bool)
CustomValidator retrieves a custom validator by name
Source Files
¶
- additionalProperties.go
- allOf.go
- anyOf.go
- compiler.go
- conditional.go
- const.go
- constructor.go
- contains.go
- content.go
- default_funcs.go
- dependentRequired.go
- dependentSchemas.go
- doc.go
- enum.go
- errors.go
- exclusiveMaximum.go
- exclusiveMinimum.go
- format.go
- formats.go
- i18n.go
- items.go
- keywords.go
- maxItems.go
- maxProperties.go
- maximum.go
- maxlength.go
- minItems.go
- minProperties.go
- minimum.go
- minlength.go
- multipleOf.go
- not.go
- oneOf.go
- pattern.go
- patternProperties.go
- prefixItems.go
- properties.go
- propertyNames.go
- rat.go
- ref.go
- required.go
- result.go
- schema.go
- struct_tags.go
- struct_validation.go
- type.go
- unevaluatedItems.go
- unevaluatedProperties.go
- uniqueItems.go
- unmarshal.go
- utils.go
- validate.go
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
schemagen
command
Package main - AST analysis functionality for schemagen.
|
Package main - AST analysis functionality for schemagen. |
|
examples
|
|
|
basic
command
Package main demonstrates basic usage of the jsonschema library.
|
Package main demonstrates basic usage of the jsonschema library. |
|
constructor
command
Package main demonstrates constructor usage of the jsonschema library.
|
Package main demonstrates constructor usage of the jsonschema library. |
|
custom-formats
command
Package main demonstrates custom-formats usage of the jsonschema library.
|
Package main demonstrates custom-formats usage of the jsonschema library. |
|
dynamic-defaults
command
Package main demonstrates dynamic default value generation with the jsonschema library.
|
Package main demonstrates dynamic default value generation with the jsonschema library. |
|
error-handling
command
Package main demonstrates error-handling usage of the jsonschema library.
|
Package main demonstrates error-handling usage of the jsonschema library. |
|
i18n
command
Package main demonstrates i18n usage of the jsonschema library.
|
Package main demonstrates i18n usage of the jsonschema library. |
|
multilingual-errors
command
Package main demonstrates multilingual-errors usage of the jsonschema library.
|
Package main demonstrates multilingual-errors usage of the jsonschema library. |
|
multiple-input-types
command
Package main demonstrates multiple-input-types usage of the jsonschema library.
|
Package main demonstrates multiple-input-types usage of the jsonschema library. |
|
struct-validation
command
Package main demonstrates struct-validation usage of the jsonschema library.
|
Package main demonstrates struct-validation usage of the jsonschema library. |
|
unmarshaling
command
Package main demonstrates unmarshaling usage of the jsonschema library.
|
Package main demonstrates unmarshaling usage of the jsonschema library. |
|
pkg
|
|
|
tagparser
Package tagparser provides shared tag parsing functionality for schemagen.
|
Package tagparser provides shared tag parsing functionality for schemagen. |