Documentation
¶
Overview ¶
Package pedantigo provides Pydantic-inspired validation for Go with struct tags, JSON schema generation, and performance optimizations.
Basic usage:
type User struct {
Email string `json:"email" validate:"required,email"`
Age int `json:"age" validate:"min=18,max=120"`
}
validator := pedantigo.New[User]()
user, errs := validator.Unmarshal(jsonData)
Package pedantigo provides Pydantic-inspired validation for Go.
Index ¶
- Constants
- func Dict[T any](obj *T) (map[string]interface{}, error)
- func Marshal[T any](obj *T) ([]byte, error)
- func MarshalWithOptions[T any](obj *T, opts MarshalOptions) ([]byte, error)
- func NewModel[T any](input any) (*T, error)
- func RegisterStructValidation[T any](fn StructLevelFunc[T]) error
- func RegisterValidation(name string, fn ValidationFunc) error
- func Schema[T any]() *jsonschema.Schema
- func SchemaJSON[T any]() ([]byte, error)
- func SchemaJSONOpenAPI[T any]() ([]byte, error)
- func SchemaOpenAPI[T any]() *jsonschema.Schema
- func Unmarshal[T any](data []byte) (*T, error)
- func Validate[T any](obj *T) error
- type ExtraFieldsMode
- type FieldError
- type MarshalOptions
- type SecretBytes
- type SecretStr
- type StreamParser
- type StreamState
- type StructLevelFunc
- type UnionOptions
- type UnionValidator
- type UnionVariant
- type Validatable
- type ValidationError
- type ValidationFunc
- type Validator
- func (v *Validator[T]) Dict(obj *T) (map[string]interface{}, error)
- func (v *Validator[T]) Marshal(obj *T) ([]byte, error)
- func (v *Validator[T]) MarshalWithOptions(obj *T, opts MarshalOptions) ([]byte, error)
- func (v *Validator[T]) NewModel(input any) (*T, error)
- func (v *Validator[T]) Schema() *jsonschema.Schema
- func (v *Validator[T]) SchemaJSON() ([]byte, error)
- func (v *Validator[T]) SchemaJSONOpenAPI() ([]byte, error)
- func (v *Validator[T]) SchemaOpenAPI() *jsonschema.Schema
- func (v *Validator[T]) Unmarshal(data []byte) (*T, error)
- func (v *Validator[T]) Validate(obj *T) error
- type ValidatorOptions
Constants ¶
const ( // ErrMsgUnknownField is returned when ExtraForbid encounters unknown JSON fields. ErrMsgUnknownField = "unknown field in JSON" // ErrMsgConstMismatch is returned when a value doesn't match the expected constant. ErrMsgConstMismatch = "must be equal to %s" // ErrMsgMissingDiscriminator is returned when discriminator field is missing from JSON. ErrMsgMissingDiscriminator = "discriminator field %q is missing" // ErrMsgUnknownDiscriminator is returned when discriminator value doesn't match any variant. ErrMsgUnknownDiscriminator = "unknown discriminator value %q for field %q" )
Error message constants for validation errors.
Variables ¶
This section is empty.
Functions ¶
func Dict ¶
Dict converts a struct into a map[string]interface{}. It uses a cached validator for type T, creating one if necessary.
Example:
user := &User{Email: "test@example.com", Age: 25}
dict, err := pedantigo.Dict(user)
// dict["email"] == "test@example.com"
// dict["age"] == 25
func Marshal ¶
Marshal validates and marshals a struct to JSON using default options. It uses a cached validator for type T, creating one if necessary.
Example:
user := &User{Email: "test@example.com", Age: 25}
jsonData, err := pedantigo.Marshal(user)
if err != nil {
// Handle validation or marshal error
}
func MarshalWithOptions ¶
func MarshalWithOptions[T any](obj *T, opts MarshalOptions) ([]byte, error)
MarshalWithOptions validates and marshals a struct to JSON with custom options. Options allow context-based field exclusion and omitzero behavior. It uses a cached validator for type T, creating one if necessary.
Example:
user := &User{Email: "test@example.com", Password: "secret"}
opts := pedantigo.ForContext("api") // Excludes password if tagged with exclude:api
jsonData, err := pedantigo.MarshalWithOptions(user, opts)
func NewModel ¶
NewModel creates a validated instance of T from various input types. Accepts: []byte (JSON), T (struct), *T (pointer), or map[string]any (kwargs). It uses a cached validator for type T, creating one if necessary.
Example:
// From JSON bytes
user, err := pedantigo.NewModel[User](jsonData)
// From map (kwargs pattern)
user, err := pedantigo.NewModel[User](map[string]any{
"email": "test@example.com",
"age": 25,
})
// From existing struct (validates it)
existing := User{Email: "test@example.com"}
user, err := pedantigo.NewModel[User](existing)
func RegisterStructValidation ¶
func RegisterStructValidation[T any](fn StructLevelFunc[T]) error
RegisterStructValidation registers a struct-level validator for type T. The validator function will be called after field-level validation succeeds. Returns an error if the function is nil or if a validator is already registered for type T.
func RegisterValidation ¶
func RegisterValidation(name string, fn ValidationFunc) error
RegisterValidation registers a custom field-level validator with the given name. The validator function will be called during validation for fields tagged with this name. Returns an error if the name is empty, the function is nil, or if the name conflicts with a built-in validator.
func Schema ¶
func Schema[T any]() *jsonschema.Schema
Schema returns the JSON Schema for type T using a cached validator. The schema is cached within the validator for maximum performance.
Example:
schema := pedantigo.Schema[User]() // schema contains the full JSON Schema object
func SchemaJSON ¶
SchemaJSON returns the JSON Schema for type T as JSON bytes. The schema is cached within the validator for maximum performance.
Example:
schemaBytes, err := pedantigo.SchemaJSON[User]()
if err != nil {
// Handle error
}
func SchemaJSONOpenAPI ¶
SchemaJSONOpenAPI returns an OpenAPI-compatible JSON Schema as JSON bytes. This version includes OpenAPI-specific enhancements like nullable support.
Example:
schemaBytes, err := pedantigo.SchemaJSONOpenAPI[User]()
if err != nil {
// Handle error
}
func SchemaOpenAPI ¶
func SchemaOpenAPI[T any]() *jsonschema.Schema
SchemaOpenAPI returns an OpenAPI-compatible JSON Schema for type T. This version includes OpenAPI-specific enhancements like nullable support.
Example:
schema := pedantigo.SchemaOpenAPI[User]() // Use in OpenAPI specification
func Unmarshal ¶
Unmarshal unmarshals JSON data into a validated struct of type T. It uses a cached validator for type T, creating one if necessary. This is equivalent to calling New[T]().Unmarshal(data) but with automatic caching.
Example:
user, err := pedantigo.Unmarshal[User](jsonData)
if err != nil {
// Handle validation errors
}
Types ¶
type ExtraFieldsMode ¶
type ExtraFieldsMode int
ExtraFieldsMode controls how unknown JSON fields are handled during Unmarshal.
const ( // ExtraIgnore ignores unknown JSON fields (default behavior). ExtraIgnore ExtraFieldsMode = iota // ExtraForbid rejects JSON with unknown fields. ExtraForbid // ExtraAllow stores unknown fields (reserved for future use). ExtraAllow )
type FieldError ¶
type FieldError struct {
Field string // Field path (e.g., "user.email")
Code string // Machine-readable error code (e.g., "INVALID_EMAIL")
Message string // Human-readable error message
Value any // The value that failed validation
}
FieldError represents a single field validation error.
type MarshalOptions ¶
type MarshalOptions struct {
// Context specifies which exclusion context to apply.
// Fields tagged with pedantigo:"exclude:context" will be omitted.
// Empty string means no context-based exclusion.
Context string
// OmitZero controls whether fields with omitzero tag and zero values are omitted.
// Default: true (honor omitzero tags)
OmitZero bool
}
MarshalOptions configures Marshal behavior.
func DefaultMarshalOptions ¶
func DefaultMarshalOptions() MarshalOptions
DefaultMarshalOptions returns sensible defaults.
func ForContext ¶
func ForContext(ctx string) MarshalOptions
ForContext creates MarshalOptions for a specific exclusion context.
type SecretBytes ¶
type SecretBytes struct {
// contains filtered or unexported fields
}
SecretBytes masks sensitive byte data in JSON output and logs. Use SecretBytes for binary secrets like encryption keys. The JSON input must be base64-encoded.
Example:
type Config struct {
EncryptionKey SecretBytes `json:"encryption_key" validate:"required"`
}
func NewSecretBytes ¶
func NewSecretBytes(b []byte) SecretBytes
NewSecretBytes creates a new SecretBytes from a byte slice.
func (SecretBytes) MarshalJSON ¶
func (s SecretBytes) MarshalJSON() ([]byte, error)
MarshalJSON returns a masked value for JSON serialization.
func (SecretBytes) String ¶
func (s SecretBytes) String() string
String returns a masked representation (safe for logs).
func (*SecretBytes) UnmarshalJSON ¶
func (s *SecretBytes) UnmarshalJSON(data []byte) error
UnmarshalJSON stores the actual value from JSON input. Expects base64-encoded string in JSON.
func (SecretBytes) Value ¶
func (s SecretBytes) Value() []byte
Value returns the actual secret bytes.
type SecretStr ¶
type SecretStr struct {
// contains filtered or unexported fields
}
SecretStr masks sensitive string data in JSON output and logs. Use SecretStr for passwords, API keys, tokens, and other sensitive data. The actual value is preserved internally and accessible via Value().
Example:
type Config struct {
APIKey SecretStr `json:"api_key" validate:"required"`
}
// JSON output: {"api_key": "**********"}
// String() output: "**********"
// Value() output: actual API key
func NewSecretStr ¶
NewSecretStr creates a new SecretStr from a plain string.
func (SecretStr) MarshalJSON ¶
MarshalJSON returns a masked value for JSON serialization. The actual secret is never exposed in JSON output.
func (SecretStr) String ¶
String returns a masked representation (safe for logs). Implements fmt.Stringer interface.
func (*SecretStr) UnmarshalJSON ¶
UnmarshalJSON stores the actual value from JSON input. The value is preserved internally for later access via Value().
type StreamParser ¶
type StreamParser[T any] struct { // contains filtered or unexported fields }
StreamParser provides stateful parsing for streaming JSON chunks. Designed for LLM streaming APIs (Anthropic, OpenAI, etc.) Does NOT perform JSON repair - waits for complete valid JSON.
func NewStreamParser ¶
func NewStreamParser[T any](opts ...ValidatorOptions) *StreamParser[T]
NewStreamParser creates a parser for streaming JSON.
func NewStreamParserWithValidator ¶
func NewStreamParserWithValidator[T any](validator *Validator[T]) *StreamParser[T]
NewStreamParserWithValidator creates a parser with a custom validator. Use this for discriminated unions or when you need custom validator options.
func (*StreamParser[T]) Buffer ¶
func (sp *StreamParser[T]) Buffer() []byte
Buffer returns the current accumulated buffer (for debugging).
func (*StreamParser[T]) Feed ¶
func (sp *StreamParser[T]) Feed(chunk []byte) (*T, *StreamState, error)
Feed adds a new chunk of JSON data and returns the current state. Returns:
- *T: Parsed struct (nil if JSON incomplete)
- *StreamState: Completion state with tracking info
- error: Validation errors (only when complete), or nil
func (*StreamParser[T]) Reset ¶
func (sp *StreamParser[T]) Reset()
Reset clears the buffer and starts fresh.
type StreamState ¶
type StreamState struct {
// IsComplete is true if JSON parsing succeeded
IsComplete bool
// BytesReceived is the total bytes accumulated
BytesReceived int
// ParseAttempts tracks how many times parsing was attempted
ParseAttempts int
// LastError holds the most recent parse error (nil if complete)
LastError error
// PresentFields lists JSON field paths that were successfully parsed
// Only populated when IsComplete is true
PresentFields []string
}
StreamState tracks the parsing progress of streaming JSON.
func (*StreamState) HasField ¶
func (ss *StreamState) HasField(path string) bool
HasField checks if a specific field path is present in the parsed result.
type StructLevelFunc ¶
StructLevelFunc is the signature for struct-level validation functions. It receives the entire struct and returns an error if validation fails.
type UnionOptions ¶
type UnionOptions struct {
// DiscriminatorField is the JSON field name used to determine the variant type.
// For example: "type", "kind", "pet_type"
DiscriminatorField string
// Variants maps discriminator values to their corresponding Go types.
Variants []UnionVariant
}
UnionOptions configures discriminated union behavior.
type UnionValidator ¶
type UnionValidator[T any] struct { // contains filtered or unexported fields }
UnionValidator validates discriminated unions where a field determines the variant type. Stub: not yet implemented.
func NewUnion ¶
func NewUnion[T any](opts UnionOptions) (*UnionValidator[T], error)
NewUnion creates a UnionValidator for type T with discriminated union support. Stub: returns error indicating not implemented.
func (*UnionValidator[T]) Schema ¶
func (v *UnionValidator[T]) Schema() *jsonschema.Schema
Schema generates JSON Schema for the discriminated union using oneOf. Returns a schema with oneOf array containing all variant schemas, each with a const constraint on the discriminator field. Implementation.
func (*UnionValidator[T]) Unmarshal ¶
func (v *UnionValidator[T]) Unmarshal(data []byte) (any, error)
Unmarshal unmarshals JSON data into the appropriate union variant. Stub: returns error indicating not implemented.
func (*UnionValidator[T]) Validate ¶
func (v *UnionValidator[T]) Validate(obj any) error
Validate validates a union value. Stub: returns error indicating not implemented.
type UnionVariant ¶
type UnionVariant struct {
// DiscriminatorValue is the value of the discriminator field that selects this variant.
// For example, if discriminator is "type" and value is "cat", this variant handles {"type": "cat", ...}
DiscriminatorValue string
// Type is the Go struct type for this variant.
Type reflect.Type
}
UnionVariant represents a variant type in a discriminated union. It maps a discriminator value to a specific Go struct type.
func VariantFor ¶
func VariantFor[T any](discriminatorValue string) UnionVariant
VariantFor is a helper to create UnionVariant from a type parameter. Usage: VariantFor[Cat]("cat").
type Validatable ¶
type Validatable interface {
Validate() error
}
Validatable is an interface for types that implement custom validation.
type ValidationError ¶
type ValidationError struct {
Errors []FieldError
}
ValidationError represents one or more validation errors It implements the error interface for idiomatic Go error handling ValidationError represents an error condition.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
Error implements the error interface.
type ValidationFunc ¶
ValidationFunc is the signature for custom field-level validation functions. It receives the field value and param string, returns an error if validation fails.
func GetCustomValidator ¶
func GetCustomValidator(name string) (ValidationFunc, bool)
GetCustomValidator retrieves a registered custom validator by name. Returns the validator function and true if found, nil and false otherwise.
type Validator ¶
type Validator[T any] struct { // contains filtered or unexported fields }
Validator validates structs of type T.
func New ¶
func New[T any](opts ...ValidatorOptions) *Validator[T]
New creates a new Validator for type T with optional configuration.
func (*Validator[T]) MarshalWithOptions ¶
func (v *Validator[T]) MarshalWithOptions(obj *T, opts MarshalOptions) ([]byte, error)
MarshalWithOptions validates and marshals struct to JSON with options. Options allow context-based field exclusion and omitzero behavior.
func (*Validator[T]) NewModel ¶
NewModel creates a validated instance of T from various input types. Accepts: []byte (JSON), T (struct), *T (pointer), or map[string]any (kwargs). This is the unified constructor that validates regardless of input source.
func (*Validator[T]) Schema ¶
func (v *Validator[T]) Schema() *jsonschema.Schema
Schema generates a JSON Schema from the validator's type T The schema includes all validation constraints mapped to JSON Schema properties Schema implements the method.
func (*Validator[T]) SchemaJSON ¶
SchemaJSON generates JSON Schema as JSON bytes for LLM APIs Returns expanded schema with nested objects inlined (no $ref/$defs) Use this for: OpenAI function calling, Anthropic tool use, Claude structured outputs SchemaJSON implements the method.
func (*Validator[T]) SchemaJSONOpenAPI ¶
SchemaJSONOpenAPI generates JSON Schema as JSON bytes for OpenAPI/Swagger specs. Returns schema with $ref/$defs for type reusability. Use this for: OpenAPI 3.0 specs, Swagger documentation, API documentation tools. SchemaJSONOpenAPI implements the method.
func (*Validator[T]) SchemaOpenAPI ¶
func (v *Validator[T]) SchemaOpenAPI() *jsonschema.Schema
SchemaOpenAPI generates a JSON Schema with $ref support for OpenAPI/Swagger specs Returns schema with $ref/$defs for type reusability and cleaner documentation Use this for: OpenAPI 3.0 specs, Swagger documentation, API documentation tools SchemaOpenAPI implements the method.
type ValidatorOptions ¶
type ValidatorOptions struct {
// StrictMissingFields controls whether missing fields without defaults are errors
// When true (default): missing fields without defaults cause validation errors
// When false: missing fields are left as zero values (user handles with pointers)
StrictMissingFields bool
// ExtraFields controls how unknown JSON fields are handled during Unmarshal.
// Default is ExtraIgnore (unknown fields are silently ignored).
ExtraFields ExtraFieldsMode
}
ValidatorOptions configures validator behavior.
func DefaultValidatorOptions ¶
func DefaultValidatorOptions() ValidatorOptions
DefaultValidatorOptions returns the default validator options.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
constraints
Package constraints provides validation constraint types and builders for pedantigo.
|
Package constraints provides validation constraint types and builders for pedantigo. |
|
isocodes
Package isocodes provides validation for ISO standard codes including country codes (ISO 3166-1), currency codes (ISO 4217), and postal codes.
|
Package isocodes provides validation for ISO standard codes including country codes (ISO 3166-1), currency codes (ISO 4217), and postal codes. |
|
Package schemagen provides JSON Schema generation and enhancement utilities for pedantigo validators.
|
Package schemagen provides JSON Schema generation and enhancement utilities for pedantigo validators. |