gsv

package module
v0.0.0-...-e7c1bb2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 18, 2025 License: Apache-2.0 Imports: 6 Imported by: 1

README

gsv - Go Schema Validator

gsv is a Go schema validator and JSON unmarshaler intended for use with large language model tools.

Documentation

Index

Constants

View Source
const (
	ArraySchemaType                              = "array"
	MinItemsError            ValidationErrorType = "min_items"
	MaxItemsError                                = "max_items"
	RequiredArrayError                           = "required_array"
	InvalidElementTypeError                      = "invalid_element_type"
	MissingElementValueError                     = "missing_element_value"
)
View Source
const (
	StringSchemaType string = "string"
)

Variables

This section is empty.

Functions

func CompileSchema

func CompileSchema(schema interface{}, cso *CompileSchemaOpts) ([]byte, error)

CompileSchema converts a gsv schema struct into a JSON Schema

func SafeMarshal

func SafeMarshal(v any) ([]byte, error)

SafeMarshal takes any struct type, calls "Ensure" with it to validate the stored schema values, and then marshals it to json, returning a byte slice and any error that occurred

Types

type ArraySchema

type ArraySchema struct {
	// contains filtered or unexported fields
}

func Array

func Array(elementSchema Schema) *ArraySchema

func (*ArraySchema) Clone

func (a *ArraySchema) Clone() Schema

func (*ArraySchema) CompileJSONSchema

func (a *ArraySchema) CompileJSONSchema(schema *jsonschema.JSONSchema, jsonTag string) error

func (*ArraySchema) Description

func (a *ArraySchema) Description(desc string) *ArraySchema

func (*ArraySchema) IsOptional

func (a *ArraySchema) IsOptional() bool

IsOptional implements Schema.IsOptional

func (*ArraySchema) MarshalJSON

func (a *ArraySchema) MarshalJSON() ([]byte, error)

func (*ArraySchema) MaxItems

func (a *ArraySchema) MaxItems(max int, opts ...ValidationOptions) *ArraySchema

func (*ArraySchema) MinItems

func (a *ArraySchema) MinItems(min int, opts ...ValidationOptions) *ArraySchema

func (*ArraySchema) Optional

func (a *ArraySchema) Optional() *ArraySchema

func (*ArraySchema) Set

func (a *ArraySchema) Set(values ...interface{}) *ArraySchema

Set provides a type-safe way to set array values

func (*ArraySchema) UnmarshalJSON

func (a *ArraySchema) UnmarshalJSON(data []byte) error

func (*ArraySchema) Validate

func (a *ArraySchema) Validate() *ValidationResult

func (*ArraySchema) Value

func (a *ArraySchema) Value() ([]interface{}, bool)

type BoolSchema

type BoolSchema struct {
	// contains filtered or unexported fields
}

BoolSchema implements the Schema interface for booleans.

func Bool

func Bool() *BoolSchema

NewBool creates a new string validator

func (*BoolSchema) Clone

func (b *BoolSchema) Clone() Schema

Clone implements Schema.Clone by creating a deep copy of the StringSchema

func (*BoolSchema) CompileJSONSchema

func (b *BoolSchema) CompileJSONSchema(schema *jsonschema.JSONSchema, jsonTag string) error

func (*BoolSchema) Description

func (b *BoolSchema) Description(val string) *BoolSchema

func (*BoolSchema) IsOptional

func (b *BoolSchema) IsOptional() bool

func (*BoolSchema) MarshalJSON

func (b *BoolSchema) MarshalJSON() ([]byte, error)

UnmarshalJSON implements json.Unmarshaler

func (*BoolSchema) Optional

func (b *BoolSchema) Optional() *BoolSchema

Optional marks the bool field as optional

func (*BoolSchema) Set

func (b *BoolSchema) Set(v bool) *BoolSchema

func (*BoolSchema) UnmarshalJSON

func (b *BoolSchema) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler

func (*BoolSchema) Validate

func (b *BoolSchema) Validate() *ValidationResult

Validate performs the validation

func (*BoolSchema) Value

func (b *BoolSchema) Value() (bool, bool)

Value returns the validated string value

type ByteSchema

type ByteSchema = NumberSchema[uint8]

ByteSchema implements the Schema interface. In Go, a byte is an alias for uint8.

func Byte

func Byte() *ByteSchema

Byte creates a new ByteSchema for uint8 (byte) values

type CompileSchemaOpts

type CompileSchemaOpts struct {
	SchemaTitle       string
	SchemaDescription string
}

type Float32Schema

type Float32Schema = NumberSchema[float32]

Float32Schema validates float32 values

func Float32

func Float32() *Float32Schema

Float32 creates a new schema for validating float32 values

type Float64Schema

type Float64Schema = NumberSchema[float64]

Float64Schema validates float64 values

func Float64

func Float64() *Float64Schema

Float64 creates a new schema for validating float64 values

type Int16Schema

type Int16Schema = NumberSchema[int16]

Int16Schema validates int16 values

func Int16

func Int16() *Int16Schema

Int16 creates a new schema for validating int16 values

type Int32Schema

type Int32Schema = NumberSchema[int32]

Int32Schema validates int32 values

func Int32

func Int32() *Int32Schema

Int32 creates a new schema for validating int32 values

type Int64Schema

type Int64Schema = NumberSchema[int64]

Int64Schema validates int64 values

func Int64

func Int64() *Int64Schema

Int64 creates a new schema for validating int64 values

type Int8Schema

type Int8Schema = NumberSchema[int8]

Int8Schema validates int8 values

func Int8

func Int8() *Int8Schema

Int8 creates a new schema for validating int8 values

type IntSchema

type IntSchema = NumberSchema[int]

IntSchema validates int values

func Int

func Int() *IntSchema

Int creates a new schema for validating int values

type NumberSchema

type NumberSchema[T cmp.Ordered] struct {
	// contains filtered or unexported fields
}

NumberSchema implements the Schema interface. It represents a generic "number" with types implemented in int.go, uint.go, float.go, and rune.go.

func Number

func Number[T cmp.Ordered]() *NumberSchema[T]

Number creates a new number validator for a specific type

func (*NumberSchema[T]) Clone

func (n *NumberSchema[T]) Clone() Schema

func (*NumberSchema[T]) CompileJSONSchema

func (n *NumberSchema[T]) CompileJSONSchema(schema *jsonschema.JSONSchema, jsonTag string) error

func (*NumberSchema[T]) Description

func (n *NumberSchema[T]) Description(val string) *NumberSchema[T]

func (*NumberSchema[T]) IsOptional

func (n *NumberSchema[T]) IsOptional() bool

func (*NumberSchema[T]) MarshalJSON

func (n *NumberSchema[T]) MarshalJSON() ([]byte, error)

func (*NumberSchema[T]) Max

func (n *NumberSchema[T]) Max(max T, opts ...ValidationOptions) *NumberSchema[T]

func (*NumberSchema[T]) Min

func (n *NumberSchema[T]) Min(min T, opts ...ValidationOptions) *NumberSchema[T]

func (*NumberSchema[T]) Optional

func (n *NumberSchema[T]) Optional() *NumberSchema[T]

Optional marks the int field as optional

func (*NumberSchema[T]) Set

func (n *NumberSchema[T]) Set(v T) *NumberSchema[T]

func (*NumberSchema[T]) UnmarshalJSON

func (n *NumberSchema[T]) UnmarshalJSON(data []byte) error

func (*NumberSchema[T]) Validate

func (n *NumberSchema[T]) Validate() *ValidationResult

Validate performs the validation

func (*NumberSchema[T]) Value

func (n *NumberSchema[T]) Value() (T, bool)

NumberSchema

type NumberValidatorFunc

type NumberValidatorFunc[T cmp.Ordered] func(T)

type ParseOptions

type ParseOptions struct {
	StopOnFirst bool           // Stop validation on first error
	SkipMissing bool           // Skip validation of missing fields
	ErrorMode   ValidationMode // How to handle errors
}

type RuneSchema

type RuneSchema = NumberSchema[int32]

RuneSchema implements the Schema interface. In Go, a "rune" is an alias for int32 and represents a Unicode code point.

func Rune

func Rune() *RuneSchema

Byte creates a new ByteSchema for uint8 (byte) values

type Schema

type Schema interface {
	// Validate calls the schema's various registered validators and returns the
	// validation results.
	Validate() *ValidationResult

	// MarshalJSON implements the encoding/json Marshaler interface and enables
	// struct with Schemas and values to build valid JSON.
	MarshalJSON() ([]byte, error)

	// UnmarshalJSON implements the encoding/json Unmarshaler interface and enables
	// struct with Schemas and values to build valid JSON.
	UnmarshalJSON([]byte) error

	// IsOptional denotes that a given schema is optional.
	IsOptional() bool

	// TODO IsNotOptional
	// CompileJSONSchema for the JSON schema compiling
	CompileJSONSchema(schema *jsonschema.JSONSchema, jsonTag string) error

	// Clone creates a deep copy of the schema, including all validation rules
	// and current value. The new schema instance will be completely independent
	// from the original.
	Clone() Schema
	// contains filtered or unexported methods
}

Schema is the core interface for gsv.

It defines the various primitives types that can store values, build schemas, and validate data.

type StringSchema

type StringSchema struct {
	// contains filtered or unexported fields
}

StringSchema implements the Schema interface for strings.

func String

func String() *StringSchema

String creates a new string validator

func (*StringSchema) Clone

func (s *StringSchema) Clone() Schema

Clone implements Schema.Clone by creating a deep copy of the StringSchema

func (*StringSchema) CompileJSONSchema

func (s *StringSchema) CompileJSONSchema(schema *jsonschema.JSONSchema, jsonTag string) error

func (*StringSchema) Description

func (s *StringSchema) Description(val string) *StringSchema

Optional marks the string field as optional

func (*StringSchema) IsOptional

func (s *StringSchema) IsOptional() bool

Optional marks the string field as optional

func (*StringSchema) MarshalJSON

func (s *StringSchema) MarshalJSON() ([]byte, error)

UnmarshalJSON implements json.Unmarshaler

func (*StringSchema) Max

func (v *StringSchema) Max(length int, opts ...ValidationOptions) *StringSchema

Max adds maximum length validation

func (*StringSchema) Min

func (v *StringSchema) Min(length int, opts ...ValidationOptions) *StringSchema

Min adds minimum length validation

func (*StringSchema) Optional

func (s *StringSchema) Optional() *StringSchema

Optional marks the string field as optional

func (*StringSchema) Set

func (v *StringSchema) Set(s string) *StringSchema

func (*StringSchema) UnmarshalJSON

func (s *StringSchema) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler

func (*StringSchema) Validate

func (v *StringSchema) Validate() *ValidationResult

Validate performs the validation

func (*StringSchema) Value

func (s *StringSchema) Value() (string, bool)

Value returns the validated string value. This method returns ("", false) if the string value is a null pointer due to it not being set

type Uint16Schema

type Uint16Schema = NumberSchema[uint16]

Uint16Schema for uint16

func Uint16

func Uint16() *Uint16Schema

Uint16 creates a new Uint16Schema

type Uint32Schema

type Uint32Schema = NumberSchema[uint32]

Uint32Schema for uint32

func Uint32

func Uint32() *Uint32Schema

Uint32 creates a new Uint32Schema

type Uint64Schema

type Uint64Schema = NumberSchema[uint64]

Uint64Schema for uint64

func Uint64

func Uint64() *Uint64Schema

Uint64 creates a new Uint64Schema

type Uint8Schema

type Uint8Schema = NumberSchema[uint8]

Uint8Schema for uint8

func Uint8

func Uint8() *Uint8Schema

Uint8 creates a new Uint8Schema

type UintSchema

type UintSchema = NumberSchema[uint]

UintSchema for uint

func Uint

func Uint() *UintSchema

Uint creates a new UintSchema

type UintptrSchema

type UintptrSchema = NumberSchema[uintptr]

UintptrSchema for uintptr

func Uintptr

func Uintptr() *UintptrSchema

Uintptr creates a new UintptrSchema

type ValidationError

type ValidationError struct {
	Type     ValidationErrorType
	Field    string      // The field path where the error occurred
	Message  string      // Human readable message
	Expected interface{} // The expected value/constraint
	Actual   interface{} // The actual value that failed validation

}

ValidationError represents a single validation error with strong typing

type ValidationErrorType

type ValidationErrorType string

ValidationErrorType represents the specific type of validation error

const (
	BoolRequiredError    ValidationErrorType = "required"
	BoolInvalidTypeError ValidationErrorType = "invalid_type"
)
const (
	MinNumberError         ValidationErrorType = "min_number"
	MaxNumberError         ValidationErrorType = "max_number"
	RequiredNumberError    ValidationErrorType = "required_number"
	InvalidNumberTypeError ValidationErrorType = "invalid_number_type"
)
const (
	MinStringLengthError   ValidationErrorType = "min_string_length"
	MaxStringLengthError   ValidationErrorType = "max_string_length"
	RequiredStringError    ValidationErrorType = "required_string"
	InvalidStringTypeError ValidationErrorType = "invalid_string_type"
)

type ValidationMode

type ValidationMode int
const (
	ReturnAllErrors ValidationMode = iota
	ReturnFirstError
	PanicOnError
)

type ValidationOptions

type ValidationOptions struct {
	Message string
}

Options for validation rules

type ValidationResult

type ValidationResult struct {
	Errors []*ValidationError
}

ValidationResult holds all validation errors for a schema

func Parse

func Parse[T any](data []byte, t *T, opts ...ParseOptions) (*ValidationResult, error)

func (*ValidationResult) AddError

func (vr *ValidationResult) AddError(err *ValidationError)

func (*ValidationResult) Error

func (vr *ValidationResult) Error() error

Error converts the ValidationResult into a single error message This implements the error interface and provides a clean way to convert structured errors into a single error when needed

func (*ValidationResult) HasErrors

func (vr *ValidationResult) HasErrors() bool

Helper methods for ValidationResult

Directories

Path Synopsis
examples
compileschema command
jsonmarshalling command
parsing/nested command
parsing/simple command
pkg

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL