schema

package
v0.7.17 Latest Latest
Warning

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

Go to latest
Published: Mar 6, 2026 License: AGPL-3.0 Imports: 3 Imported by: 0

Documentation

Overview

Package schema provides a type-safe validation system for structured data.

It defines a simple type system with built-in types (string, int, float, bool) and support for slices and custom validators. Schemas map field names to types, enabling runtime validation of complex data structures.

Basic usage:

schema := schema.Schema{
    "api_key": schema.String(),
    "retries": schema.Int(),
    "tags":    schema.Slice(schema.String()),
}

data := map[string]any{
    "api_key": "secret123",
    "retries": 3,
    "tags":    []string{"prod", "critical"},
}

if err := schema.Validate(schema, data); err != nil {
    // Handle validation errors
}

Schemas can be created programmatically or parsed from type strings:

typeMap := map[string]string{
    "api_key": "string",
    "retries": "int",
    "tags":    "[string]",
}

schema, err := schema.ParseTypeMap(typeMap)

Custom validators can be registered for domain-specific validation:

positiveInt := schema.Custom("positive_int", func(v any) error {
    i, ok := v.(int)
    if !ok {
        return fmt.Errorf("expected int")
    }
    if i <= 0 {
        return fmt.Errorf("must be positive")
    }
    return nil
})

This package is designed to be library-agnostic, with zero external dependencies beyond the Go standard library. It can be embedded in larger systems or extracted as a standalone library.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Validate

func Validate(schema Schema, data map[string]any) error

Validate checks if data conforms to the schema. Returns an error with all validation failures found.

func ValidateFields

func ValidateFields(schema Schema, data map[string]any, fields ...string) error

ValidateFields validates only specific fields from data against the schema. Missing fields are treated as an error.

func ValidationErrors

func ValidationErrors(err error) []error

ValidationErrors returns all validation errors if err is an AggregateError. Otherwise returns nil.

Types

type AggregateError

type AggregateError struct {
	Errors []error
}

AggregateError represents multiple validation failures.

func (*AggregateError) Error

func (e *AggregateError) Error() string

type BoolType

type BoolType struct{}

BoolType validates boolean values.

func (*BoolType) Name

func (t *BoolType) Name() string

func (*BoolType) Validate

func (t *BoolType) Validate(value any) error

type CustomType

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

CustomType applies a user-defined validation function.

func (*CustomType) Name

func (t *CustomType) Name() string

func (*CustomType) Validate

func (t *CustomType) Validate(value any) error

type FloatType

type FloatType struct{}

FloatType validates floating-point values.

func (*FloatType) Name

func (t *FloatType) Name() string

func (*FloatType) Validate

func (t *FloatType) Validate(value any) error

type IntType

type IntType struct{}

IntType validates integer values.

func (*IntType) Name

func (t *IntType) Name() string

func (*IntType) Validate

func (t *IntType) Validate(value any) error

type Schema

type Schema map[string]Type

Schema is a map of field names to their expected types. Example: {"api_key": String(), "retries": Int(), "tags": Slice(String())}

func ParseTypeMap

func ParseTypeMap(typeMap map[string]string) (Schema, error)

ParseTypeMap converts a map of field names to type strings into a Schema. Example: {"api_key": "string", "retries": "int"}

func (Schema) MarshalJSON

func (s Schema) MarshalJSON() ([]byte, error)

MarshalJSON serializes the schema as a map of field names to type strings.

func (*Schema) UnmarshalJSON

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

UnmarshalJSON deserializes the schema from a map of field names to type strings.

type SliceType

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

SliceType validates slices of a specific element type.

func (*SliceType) Name

func (t *SliceType) Name() string

func (*SliceType) Validate

func (t *SliceType) Validate(value any) error

type StringType

type StringType struct{}

StringType validates string values.

func (*StringType) Name

func (t *StringType) Name() string

func (*StringType) Validate

func (t *StringType) Validate(value any) error

type Type

type Type interface {
	// Name returns the human-readable name of the type (e.g., "string", "int").
	Name() string
	// Validate checks if a value conforms to this type.
	Validate(value any) error
}

Type defines the contract for field validation. Implementations determine how values are validated against a type.

func Bool

func Bool() Type

Bool creates a boolean type validator.

func Custom

func Custom(name string, validate func(any) error) Type

Custom creates a custom type validator with a user-defined function.

func Float

func Float() Type

Float creates a float type validator.

func Int

func Int() Type

Int creates an integer type validator.

func ParseType

func ParseType(typeStr string) (Type, error)

ParseType converts a string type name to a Type. Supports basic types: "string", "int", "float", "bool", "[string]", "[int]", etc.

func Slice

func Slice(elemType Type) Type

Slice creates a slice type validator for elements of the given type.

func String

func String() Type

String creates a string type validator.

type ValidationError

type ValidationError struct {
	Key    string // Field name
	Reason string // Human-readable reason for failure
	Value  any    // The value that failed validation
}

ValidationError represents a single field validation failure.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Jump to

Keyboard shortcuts

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