Documentation
¶
Overview ¶
Package model provides JSON/YAML parsing with type coercion and validation.
Features: automatic format detection, type coercion, validation, and caching.
Usage ¶
type User struct {
ID int `json:"id" validate:"required,min=1"`
Name string `json:"name" validate:"required"`
Email string `json:"email" validate:"email"`
}
user, err := model.ParseInto[User](data)
Type Coercion ¶
Converts between compatible types: "42"→42, "true"→true, Unix/RFC3339→time.Time
Validation ¶
Supported validators: required, min, max, length, email, alpha, alphanum
Performance Caching ¶
parser := model.NewCachedParser[User](nil) user, _ := parser.Parse(data) // 5-27x faster for repeated inputs
See examples/ directory and docs/ for complete documentation.
Package model provides core parsing and validation functionality for gopantic. It includes type coercion, error handling, and the main ParseInto function for converting JSON data into typed Go structs.
Index ¶
- Constants
- Variables
- func AddSensitiveFieldPattern(pattern string)
- func ClearValidationCache()
- func CoerceValue(value interface{}, targetType reflect.Type, fieldName string) (interface{}, error)
- func CoerceValueWithFormat(value interface{}, targetType reflect.Type, fieldName string, format Format) (interface{}, error)
- func GetMaxCacheSize() int
- func GetMaxInputSize() int
- func GetMaxStructureDepth() int
- func GetMaxValidationDepth() int
- func GetSensitiveFieldPatterns() []string
- func IsSensitiveField(fieldName string) bool
- func ParseInto[T any](raw []byte) (T, error)
- func ParseIntoWithFormat[T any](raw []byte, format Format) (T, error)
- func RegisterGlobalCrossFieldFunc(name string, validatorFunc CrossFieldValidatorFunc)
- func RegisterGlobalFunc(name string, validatorFunc ValidatorFunc)
- func SetMaxCacheSize(size int)
- func SetMaxInputSize(size int)
- func SetMaxStructureDepth(depth int)
- func SetMaxValidationDepth(depth int)
- func SetSensitiveFieldPatterns(patterns []string)
- func Validate[T any](v *T) error
- func ValidateValue(fieldName string, value interface{}, rules []ValidationRule) error
- func ValidateValueWithStruct(fieldName string, value interface{}, rules []ValidationRule, ...) error
- type AlphaValidator
- type AlphanumValidator
- type CacheConfig
- type CachedParser
- type CrossFieldValidator
- type CrossFieldValidatorFunc
- type CustomFuncValidator
- type EmailValidator
- type ErrorList
- func (el *ErrorList) Add(err error)
- func (el ErrorList) AsError() error
- func (el ErrorList) Error() string
- func (el ErrorList) GroupByField() map[string][]*ValidationError
- func (el ErrorList) HasErrors() bool
- func (el ErrorList) ToJSON() ([]byte, error)
- func (el ErrorList) ToStructuredReport() *StructuredErrorReport
- func (el ErrorList) ValidationErrors() []*ValidationError
- type FieldError
- type FieldValidation
- type Format
- type FormatParser
- type JSONParser
- type LengthValidator
- type MaxValidator
- type MinValidator
- type ParseError
- type RequiredValidator
- type StructValidation
- type StructuredErrorReport
- type ValidationError
- func NewValidationError(field string, value interface{}, rule, message string) *ValidationError
- func NewValidationErrorWithDetails(field, fieldPath string, value interface{}, rule, message string, ...) *ValidationError
- func NewValidationErrorWithPath(field, fieldPath string, value interface{}, rule, message string) *ValidationError
- type ValidationErrorInfo
- type ValidationRule
- type Validator
- type ValidatorFunc
- type ValidatorRegistry
- func (r *ValidatorRegistry) Create(name string, params map[string]interface{}) Validator
- func (r *ValidatorRegistry) ListValidators() []string
- func (r *ValidatorRegistry) Register(name string, factory func(params map[string]interface{}) Validator)
- func (r *ValidatorRegistry) RegisterCrossFieldFunc(name string, validatorFunc CrossFieldValidatorFunc)
- func (r *ValidatorRegistry) RegisterFunc(name string, validatorFunc ValidatorFunc)
- type YAMLParser
Constants ¶
const RedactedValue = "[REDACTED]"
RedactedValue is the placeholder used when sensitive field values are sanitized.
Variables ¶
var DefaultSensitivePatterns = []string{
"password", "passwd", "secret", "token",
"key", "credential", "auth", "api_key",
"apikey", "private", "bearer",
}
DefaultSensitivePatterns contains field name patterns that indicate sensitive data. These patterns are matched case-insensitively as substrings of field names. Fields matching these patterns will have their values redacted in error output.
var MaxCacheSize = 1000
MaxCacheSize is the maximum number of struct types to cache validation metadata for. When the cache size exceeds this limit, the oldest entries are removed (FIFO). Set to 0 for unlimited caching (not recommended for long-running services). Default: 1000 types.
WARNING: Direct modification of this variable is NOT thread-safe. For concurrent access, use GetMaxCacheSize() and SetMaxCacheSize().
var MaxInputSize = 10 * 1024 * 1024 // 10MB
MaxInputSize is the default maximum size for input data (10MB). Set to 0 to disable size checking. This prevents resource exhaustion from maliciously large inputs.
WARNING: Direct modification of this variable is NOT thread-safe. For concurrent access, use GetMaxInputSize() and SetMaxInputSize().
var MaxStructureDepth = 64
MaxStructureDepth is the default maximum nesting depth for parsed structures (64). Set to 0 to disable depth checking. This prevents resource exhaustion from deeply nested JSON/YAML structures.
WARNING: Direct modification of this variable is NOT thread-safe. For concurrent access, use GetMaxStructureDepth() and SetMaxStructureDepth().
var MaxValidationDepth = 32
MaxValidationDepth is the maximum depth of nested struct validation. This prevents stack overflow and DoS attacks from deeply nested structures. Default: 32 levels.
WARNING: Direct modification of this variable is NOT thread-safe. For concurrent access, use GetMaxValidationDepth() and SetMaxValidationDepth().
Functions ¶
func AddSensitiveFieldPattern ¶
func AddSensitiveFieldPattern(pattern string)
AddSensitiveFieldPattern adds a pattern to the sensitive field patterns in a thread-safe manner. The pattern is matched case-insensitively as a substring of field names.
func ClearValidationCache ¶
func ClearValidationCache()
ClearValidationCache clears the cached validation metadata for all types. This is useful when you register new custom validators and want to ensure they are applied to types that have already been parsed. In normal operation, you should not need to call this function.
func CoerceValue ¶
CoerceValue attempts to coerce a value to the target type with intelligent type conversion. Uses JSON format assumptions by default. Supports conversion between strings, numbers, booleans, time.Time, slices, arrays, and nested structs.
Example:
result, err := model.CoerceValue("123", reflect.TypeOf(0), "user_id")
// result will be int(123)
func CoerceValueWithFormat ¶
func CoerceValueWithFormat(value interface{}, targetType reflect.Type, fieldName string, format Format) (interface{}, error)
CoerceValueWithFormat attempts to coerce a value to the target type with format-specific awareness. Different formats may have different type coercion rules and conventions. This is the core type coercion function used by all parsing operations.
Supported conversions include: - String <-> numeric types (int, float, etc.) - String <-> bool (true/false, 1/0, yes/no, etc.) - String/numeric -> time.Time (various formats) - Array/slice element coercion - Map -> struct conversion with nested coercion
func GetMaxCacheSize ¶
func GetMaxCacheSize() int
GetMaxCacheSize returns the maximum cache size in a thread-safe manner. Default: 1000 types.
func GetMaxInputSize ¶
func GetMaxInputSize() int
GetMaxInputSize returns the maximum input size in a thread-safe manner. Default: 10MB (10 * 1024 * 1024 bytes). Set to 0 to disable size checking.
func GetMaxStructureDepth ¶
func GetMaxStructureDepth() int
GetMaxStructureDepth returns the maximum structure nesting depth in a thread-safe manner. Default: 64 levels. Set to 0 to disable depth checking.
func GetMaxValidationDepth ¶
func GetMaxValidationDepth() int
GetMaxValidationDepth returns the maximum validation depth in a thread-safe manner. Default: 32 levels.
func GetSensitiveFieldPatterns ¶
func GetSensitiveFieldPatterns() []string
GetSensitiveFieldPatterns returns the current sensitive field patterns in a thread-safe manner. Returns a copy of the patterns slice to prevent external modification.
func IsSensitiveField ¶
IsSensitiveField checks if a field name matches any sensitive field pattern. Matching is case-insensitive and checks if the pattern is a substring of the field name. Returns true if the field should be considered sensitive and its value redacted.
Example:
IsSensitiveField("Password") // true (matches "password")
IsSensitiveField("user_api_key") // true (matches "api_key")
IsSensitiveField("username") // false
func ParseInto ¶
ParseInto parses raw data into a struct of type T with automatic format detection, type coercion, and validation. The format is automatically detected (JSON or YAML) based on the content structure. This is the main entry point for parsing operations in gopantic.
The function checks input size against MaxInputSize (default 10MB) to prevent resource exhaustion. Set MaxInputSize to 0 to disable size checking.
Example:
type User struct {
ID int `json:"id" validate:"required,min=1"`
Name string `json:"name" validate:"required,min=2"`
}
user, err := model.ParseInto[User](jsonData)
if err != nil {
log.Fatal(err)
}
func ParseIntoWithFormat ¶
ParseIntoWithFormat parses raw data of a specific format into a struct of type T with type coercion and validation. Use this when you know the exact format or want to enforce a specific format. Supports JSON and YAML formats.
The function checks input size against MaxInputSize (default 10MB) to prevent resource exhaustion. Set MaxInputSize to 0 to disable size checking.
Example:
user, err := model.ParseIntoWithFormat[User](yamlData, model.FormatYAML)
if err != nil {
log.Fatal(err)
}
func RegisterGlobalCrossFieldFunc ¶
func RegisterGlobalCrossFieldFunc(name string, validatorFunc CrossFieldValidatorFunc)
RegisterGlobalCrossFieldFunc is a convenience function to register a cross-field validation function to the default global registry.
Note: If you register custom validators after types have been parsed, you should call ClearValidationCache() to ensure new validators are used for all subsequent parses.
Example usage:
model.RegisterGlobalCrossFieldFunc("password_match", func(fieldName string, fieldValue interface{}, structValue reflect.Value, params map[string]interface{}) error {
passwordField := structValue.FieldByName("Password")
if !passwordField.IsValid() {
return model.NewValidationError(fieldName, fieldValue, "password_match", "Password field not found")
}
password := passwordField.Interface().(string)
confirmPassword, ok := fieldValue.(string)
if !ok {
return model.NewValidationError(fieldName, fieldValue, "password_match", "value must be a string")
}
if password != confirmPassword {
return model.NewValidationError(fieldName, fieldValue, "password_match", "passwords do not match")
}
return nil
})
func RegisterGlobalFunc ¶
func RegisterGlobalFunc(name string, validatorFunc ValidatorFunc)
RegisterGlobalFunc is a convenience function to register a custom validation function to the default global registry.
Note: If you register custom validators after types have been parsed, you should call ClearValidationCache() to ensure new validators are used for all subsequent parses.
Example usage:
model.RegisterGlobalFunc("password_strength", func(fieldName string, value interface{}, params map[string]interface{}) error {
password, ok := value.(string)
if !ok || password == "" {
return nil // handled by required validator
}
if len(password) < 8 {
return model.NewValidationError(fieldName, value, "password_strength", "password must be at least 8 characters")
}
hasUpper := strings.ContainsAny(password, "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
hasLower := strings.ContainsAny(password, "abcdefghijklmnopqrstuvwxyz")
hasDigit := strings.ContainsAny(password, "0123456789")
if !hasUpper || !hasLower || !hasDigit {
return model.NewValidationError(fieldName, value, "password_strength", "password must contain uppercase, lowercase, and numeric characters")
}
return nil
})
func SetMaxCacheSize ¶
func SetMaxCacheSize(size int)
SetMaxCacheSize sets the maximum cache size in a thread-safe manner. Set to 0 for unlimited caching (not recommended for long-running services).
Note: This also updates the exported MaxCacheSize variable for compatibility, but that update is not atomic with respect to direct variable reads.
func SetMaxInputSize ¶
func SetMaxInputSize(size int)
SetMaxInputSize sets the maximum input size in a thread-safe manner. Set to 0 to disable size checking.
Note: This also updates the exported MaxInputSize variable for compatibility, but that update is not atomic with respect to direct variable reads.
func SetMaxStructureDepth ¶
func SetMaxStructureDepth(depth int)
SetMaxStructureDepth sets the maximum structure nesting depth in a thread-safe manner. This prevents resource exhaustion from deeply nested JSON/YAML structures.
Note: This also updates the exported MaxStructureDepth variable for compatibility, but that update is not atomic with respect to direct variable reads.
func SetMaxValidationDepth ¶
func SetMaxValidationDepth(depth int)
SetMaxValidationDepth sets the maximum validation depth in a thread-safe manner. This prevents stack overflow and DoS attacks from deeply nested structures.
Note: This also updates the exported MaxValidationDepth variable for compatibility, but that update is not atomic with respect to direct variable reads.
func SetSensitiveFieldPatterns ¶
func SetSensitiveFieldPatterns(patterns []string)
SetSensitiveFieldPatterns sets the sensitive field patterns in a thread-safe manner. Pass nil or empty slice to disable sensitive field detection. Pass custom patterns to override the defaults.
Example:
model.SetSensitiveFieldPatterns([]string{"password", "secret", "ssn", "credit_card"})
func Validate ¶
Validate validates a struct using gopantic validation rules defined in struct tags. This function can be used independently of parsing, allowing you to validate structs that were populated from any source (JSON, YAML, database, environment variables, etc.).
Example:
type User struct {
ID int `json:"id" validate:"required,min=1"`
Name string `json:"name" validate:"required,min=2"`
}
user := User{ID: 42, Name: "Alice"}
if err := model.Validate(&user); err != nil {
log.Fatal(err)
}
func ValidateValue ¶
func ValidateValue(fieldName string, value interface{}, rules []ValidationRule) error
ValidateValue applies validation rules to a single value. This function runs all validation rules and aggregates any errors. Use this for simple field validation without cross-field dependencies.
func ValidateValueWithStruct ¶
func ValidateValueWithStruct(fieldName string, value interface{}, rules []ValidationRule, structValue reflect.Value) error
ValidateValueWithStruct applies validation rules to a single value with access to the full struct. This function supports both regular and cross-field validators, making it suitable for complex validation scenarios that require access to other fields in the struct.
Types ¶
type AlphaValidator ¶
type AlphaValidator struct{}
AlphaValidator checks that a string contains only alphabetic characters
func (*AlphaValidator) Name ¶
func (v *AlphaValidator) Name() string
Name returns the validator name
func (*AlphaValidator) Validate ¶
func (v *AlphaValidator) Validate(fieldName string, value interface{}) error
Validate checks if the value contains only alphabetic characters
type AlphanumValidator ¶
type AlphanumValidator struct{}
AlphanumValidator checks that a string contains only alphanumeric characters
func (*AlphanumValidator) Name ¶
func (v *AlphanumValidator) Name() string
Name returns the validator name
func (*AlphanumValidator) Validate ¶
func (v *AlphanumValidator) Validate(fieldName string, value interface{}) error
Validate checks if the value contains only alphanumeric characters
type CacheConfig ¶
type CacheConfig struct {
TTL time.Duration // Time to live for cached entries (default: 1 hour)
MaxEntries int // Maximum number of cached entries (default: 1000)
CleanupInterval time.Duration // How often to run cleanup (default: TTL/2, 0 to disable)
}
CacheConfig holds basic cache configuration
func DefaultCacheConfig ¶
func DefaultCacheConfig() *CacheConfig
DefaultCacheConfig returns sensible defaults for in-memory caching
type CachedParser ¶
type CachedParser[T any] struct { // contains filtered or unexported fields }
CachedParser provides simple in-memory caching for parsing results
func NewCachedParser ¶
func NewCachedParser[T any](config *CacheConfig) *CachedParser[T]
NewCachedParser creates a new cached parser with optional configuration. If CleanupInterval > 0, a background goroutine will periodically clean expired entries. Call Close() when done to stop the cleanup goroutine.
func (*CachedParser[T]) ClearCache ¶
func (cp *CachedParser[T]) ClearCache()
ClearCache removes all cached entries
func (*CachedParser[T]) Close ¶
func (cp *CachedParser[T]) Close()
Close stops the background cleanup goroutine if running. After calling Close, the parser can still be used but expired entries will only be cleaned up on access rather than proactively.
func (*CachedParser[T]) Parse ¶
func (cp *CachedParser[T]) Parse(data []byte) (T, error)
Parse parses data with caching support
func (*CachedParser[T]) ParseWithFormat ¶
func (cp *CachedParser[T]) ParseWithFormat(data []byte, format Format) (T, error)
ParseWithFormat parses data with format specification and caching
func (*CachedParser[T]) Stats ¶
func (cp *CachedParser[T]) Stats() (size, maxSize int, hitRate float64)
Stats returns cache statistics including size, max size, and hit rate
type CrossFieldValidator ¶
type CrossFieldValidator struct {
// contains filtered or unexported fields
}
CrossFieldValidator wraps a CrossFieldValidatorFunc to implement special validation interface
func (*CrossFieldValidator) Name ¶
func (v *CrossFieldValidator) Name() string
Name returns the name of the cross-field validator
func (*CrossFieldValidator) Validate ¶
func (v *CrossFieldValidator) Validate(fieldName string, value interface{}) error
Validate returns an error as cross-field validators require full struct context
func (*CrossFieldValidator) ValidateWithStruct ¶
func (v *CrossFieldValidator) ValidateWithStruct(fieldName string, fieldValue interface{}, structValue reflect.Value) error
ValidateWithStruct performs cross-field validation with access to the full struct
type CrossFieldValidatorFunc ¶
type CrossFieldValidatorFunc func(fieldName string, fieldValue interface{}, structValue reflect.Value, params map[string]interface{}) error
CrossFieldValidatorFunc represents a validation function that has access to the entire struct. Use RegisterGlobalCrossFieldFunc for validators that need to access other fields for validation.
type CustomFuncValidator ¶
type CustomFuncValidator struct {
// contains filtered or unexported fields
}
CustomFuncValidator wraps a ValidatorFunc to implement the Validator interface
func (*CustomFuncValidator) Name ¶
func (v *CustomFuncValidator) Name() string
Name returns the name of the custom validator
func (*CustomFuncValidator) Validate ¶
func (v *CustomFuncValidator) Validate(fieldName string, value interface{}) error
Validate executes the custom validation function
type EmailValidator ¶
type EmailValidator struct{}
EmailValidator validates email addresses using a simple but practical regex
func (*EmailValidator) Name ¶
func (v *EmailValidator) Name() string
Name returns the validator name
func (*EmailValidator) Validate ¶
func (v *EmailValidator) Validate(fieldName string, value interface{}) error
Validate checks if the value is a valid email address
type ErrorList ¶
type ErrorList []error
ErrorList represents a collection of errors that can occur during parsing/validation. Provides aggregation, JSON serialization, and structured error reporting capabilities.
func (*ErrorList) Add ¶
Add appends an error to the ErrorList If the error is itself an ErrorList, it flattens the errors to avoid nesting
func (ErrorList) AsError ¶
AsError returns the ErrorList as an error if it contains any errors, nil otherwise
func (ErrorList) GroupByField ¶
func (el ErrorList) GroupByField() map[string][]*ValidationError
GroupByField groups validation errors by field path
func (ErrorList) ToStructuredReport ¶
func (el ErrorList) ToStructuredReport() *StructuredErrorReport
ToStructuredReport converts an ErrorList to a structured error report for JSON serialization
func (ErrorList) ValidationErrors ¶
func (el ErrorList) ValidationErrors() []*ValidationError
ValidationErrors returns only the ValidationError instances from the ErrorList
type FieldError ¶
type FieldError struct {
Field string `json:"field"`
FieldPath string `json:"field_path"`
Value interface{} `json:"value,omitempty"`
Errors []ValidationErrorInfo `json:"validation_errors"`
}
FieldError represents a single field's validation errors. Groups all validation errors for a specific field with detailed context information.
type FieldValidation ¶
type FieldValidation struct {
FieldName string // Name of the struct field
JSONKey string // JSON key for this field
Rules []ValidationRule // List of validation rules to apply
}
FieldValidation contains all validation rules for a single struct field. Used internally to organize validation rules by field during parsing.
type Format ¶
type Format int
Format represents the input data format for parsing operations. Supports JSON and YAML formats with automatic detection capabilities.
func DetectFormat ¶
DetectFormat automatically detects the format of the given raw data. Uses heuristic analysis to distinguish between JSON and YAML formats. Returns FormatJSON as the default for ambiguous cases.
Example:
format := model.DetectFormat(data) result, err := model.ParseIntoWithFormat[MyStruct](data, format)
type FormatParser ¶
type FormatParser interface {
// Parse parses raw bytes into a generic interface{} structure
// Can return map[string]interface{} for objects or []interface{} for arrays
Parse(raw []byte) (interface{}, error)
// Format returns the format type this parser handles
Format() Format
}
FormatParser defines the interface for parsing different data formats. Implementations handle format-specific parsing logic while providing a consistent interface for the core parsing engine.
func GetParser ¶
func GetParser(format Format) FormatParser
GetParser returns the appropriate parser instance for the given format. This function provides access to format-specific parsers for advanced use cases.
Example:
parser := model.GetParser(model.FormatJSON) data, err := parser.Parse(rawBytes)
type JSONParser ¶
type JSONParser struct{}
JSONParser implements FormatParser for JSON format. Provides high-performance JSON parsing with standard library compatibility.
func (*JSONParser) Format ¶
func (jp *JSONParser) Format() Format
Format returns the JSON format type
func (*JSONParser) Parse ¶
func (jp *JSONParser) Parse(raw []byte) (interface{}, error)
Parse parses JSON data into a generic interface{}
type LengthValidator ¶
type LengthValidator struct {
Length int
}
LengthValidator checks exact length for strings and arrays
func (*LengthValidator) Name ¶
func (v *LengthValidator) Name() string
Name returns the validator name
func (*LengthValidator) Validate ¶
func (v *LengthValidator) Validate(fieldName string, value interface{}) error
Validate checks if the value has the exact required length
type MaxValidator ¶
type MaxValidator struct {
Max float64
}
MaxValidator checks that a numeric value or string length is at most the maximum
func (*MaxValidator) Validate ¶
func (v *MaxValidator) Validate(fieldName string, value interface{}) error
Validate checks that a numeric value or string length is at most the maximum
type MinValidator ¶
type MinValidator struct {
Min float64
}
MinValidator checks that a numeric value or string length is at least the minimum
func (*MinValidator) Validate ¶
func (v *MinValidator) Validate(fieldName string, value interface{}) error
Validate checks that a numeric value or string length is at least the minimum
type ParseError ¶
ParseError represents an error that occurred during data parsing. Contains detailed information about the field, value, and target type that caused the error.
func NewParseError ¶
func NewParseError(field string, value interface{}, targetType, message string) *ParseError
NewParseError creates a new ParseError with detailed context information. Use this to create meaningful error messages for parsing failures.
func (ParseError) Error ¶
func (e ParseError) Error() string
type RequiredValidator ¶
type RequiredValidator struct{}
RequiredValidator checks that a field has a non-zero value
func (*RequiredValidator) Name ¶
func (v *RequiredValidator) Name() string
Name returns the validator name
func (*RequiredValidator) Validate ¶
func (v *RequiredValidator) Validate(fieldName string, value interface{}) error
Validate checks that a field has a non-zero value
type StructValidation ¶
type StructValidation struct {
Fields []FieldValidation // Validation rules for each field
}
StructValidation contains validation information for an entire struct. Generated by ParseValidationTags and used during the validation phase.
func ParseValidationTags ¶
func ParseValidationTags(structType reflect.Type) *StructValidation
ParseValidationTags parses validation tags from a struct and returns validation info. This function analyzes struct tags and builds the validation rules for efficient validation. The returned StructValidation is automatically cached by type for performance. Subsequent calls with the same type will return the cached result.
type StructuredErrorReport ¶
type StructuredErrorReport struct {
Errors []FieldError `json:"errors"`
Count int `json:"count"`
}
StructuredErrorReport represents a structured validation error report for JSON serialization. Provides a comprehensive, machine-readable format for validation errors suitable for APIs.
type ValidationError ¶
type ValidationError struct {
Field string
FieldPath string // Full field path for nested structures (e.g., "User.Address.Street")
Value interface{}
Rule string
Message string
Details map[string]interface{} // Additional structured information
}
ValidationError represents a validation failure with detailed field and rule information. Supports nested field paths and structured error details for comprehensive error reporting.
func NewValidationError ¶
func NewValidationError(field string, value interface{}, rule, message string) *ValidationError
NewValidationError creates a new ValidationError with basic field and rule information. This is the most commonly used constructor for validation errors.
func NewValidationErrorWithDetails ¶
func NewValidationErrorWithDetails(field, fieldPath string, value interface{}, rule, message string, details map[string]interface{}) *ValidationError
NewValidationErrorWithDetails creates a new ValidationError with additional structured details. The details map can contain additional context information for advanced error reporting scenarios.
func NewValidationErrorWithPath ¶
func NewValidationErrorWithPath(field, fieldPath string, value interface{}, rule, message string) *ValidationError
NewValidationErrorWithPath creates a new ValidationError with explicit field path for nested structures. Use this when validating nested structs to provide clear error paths like "User.Address.Street".
func (ValidationError) Error ¶
func (e ValidationError) Error() string
func (ValidationError) SanitizedValue ¶
func (e ValidationError) SanitizedValue() interface{}
SanitizedValue returns the error value with sensitive data redacted. If the field name matches any sensitive pattern, returns RedactedValue ("[REDACTED]"). Otherwise returns the original value unchanged.
type ValidationErrorInfo ¶
type ValidationErrorInfo struct {
Rule string `json:"rule"`
Message string `json:"message"`
Details map[string]interface{} `json:"details,omitempty"`
}
ValidationErrorInfo represents detailed information about a validation error. Contains the rule name, message, and optional additional details for comprehensive error reporting.
type ValidationRule ¶
type ValidationRule struct {
Name string // Name of the validator (e.g., "min")
Validator Validator // The validator instance
Parameters map[string]interface{} // Parameters for the validator (e.g., {"value": 5})
}
ValidationRule represents a single validation rule parsed from struct tags. Contains the validator instance and any parameters specified in the tag.
type Validator ¶
type Validator interface {
// Validate checks if the value is valid according to this validator's rules
Validate(fieldName string, value interface{}) error
// Name returns the name of this validator (e.g., "required", "min", "email")
Name() string
}
Validator represents a validation rule that can be applied to a field. Implement this interface to create custom validators for specific validation logic.
type ValidatorFunc ¶
ValidatorFunc represents a custom validation function for field-level validation. Use RegisterGlobalFunc to register custom validators that can be used in struct tags.
type ValidatorRegistry ¶
type ValidatorRegistry struct {
// contains filtered or unexported fields
}
ValidatorRegistry manages the collection of available validators. Provides registration and lookup capabilities for built-in and custom validators.
func GetDefaultRegistry ¶
func GetDefaultRegistry() *ValidatorRegistry
GetDefaultRegistry returns the default global validator registry. This registry contains all built-in validators and any custom validators registered via RegisterGlobalFunc and RegisterGlobalCrossFieldFunc.
func NewValidatorRegistry ¶
func NewValidatorRegistry() *ValidatorRegistry
NewValidatorRegistry creates a new validator registry with built-in validators. Includes required, min, max, email, length, alpha, and alphanum validators.
func (*ValidatorRegistry) Create ¶
func (r *ValidatorRegistry) Create(name string, params map[string]interface{}) Validator
Create creates a validator instance from the registry
func (*ValidatorRegistry) ListValidators ¶
func (r *ValidatorRegistry) ListValidators() []string
ListValidators returns a list of all registered validator names (built-in, custom, and cross-field)
func (*ValidatorRegistry) Register ¶
func (r *ValidatorRegistry) Register(name string, factory func(params map[string]interface{}) Validator)
Register adds a new validator to the registry
func (*ValidatorRegistry) RegisterCrossFieldFunc ¶
func (r *ValidatorRegistry) RegisterCrossFieldFunc(name string, validatorFunc CrossFieldValidatorFunc)
RegisterCrossFieldFunc adds a cross-field validation function to the registry. Cross-field validators have access to the entire struct and can validate relationships between fields.
Example usage:
registry.RegisterCrossFieldFunc("password_match", func(fieldName string, fieldValue interface{}, structValue reflect.Value, params map[string]interface{}) error {
password := structValue.FieldByName("Password").Interface().(string)
confirmPassword, ok := fieldValue.(string)
if !ok {
return model.NewValidationError(fieldName, fieldValue, "password_match", "value must be a string")
}
if password != confirmPassword {
return model.NewValidationError(fieldName, fieldValue, "password_match", "passwords do not match")
}
return nil
})
func (*ValidatorRegistry) RegisterFunc ¶
func (r *ValidatorRegistry) RegisterFunc(name string, validatorFunc ValidatorFunc)
RegisterFunc adds a custom validation function to the registry. Custom functions provide a simpler API for common validation cases.
Example usage:
registry := model.GetDefaultRegistry()
registry.RegisterFunc("contains", func(fieldName string, value interface{}, params map[string]interface{}) error {
str, ok := value.(string)
if !ok {
return fmt.Errorf("value must be a string")
}
substring, ok := params["value"].(string)
if !ok {
return fmt.Errorf("contains validator requires a string parameter")
}
if !strings.Contains(str, substring) {
return model.NewValidationError(fieldName, value, "contains",
fmt.Sprintf("value must contain '%s'", substring))
}
return nil
})
type YAMLParser ¶
type YAMLParser struct{}
YAMLParser implements FormatParser for YAML format. Supports all YAML 1.2 features including documents, arrays, and nested structures.
func (*YAMLParser) Format ¶
func (yp *YAMLParser) Format() Format
Format returns the YAML format type
func (*YAMLParser) Parse ¶
func (yp *YAMLParser) Parse(raw []byte) (interface{}, error)
Parse parses YAML data into a generic interface{}