API Reference
Core Functions
ParseInto
Parses JSON or YAML with automatic format detection, type coercion, and validation.
ParseIntoWithFormat
Parses with explicit format (FormatJSON or FormatYAML).
Validate
Validates an already-parsed struct.
Format Detection
DetectFormat
Auto-detects JSON or YAML format. Looks for JSON markers ({, [), YAML markers (---, :), defaults to JSON for ambiguous cases.
Caching
NewCachedParser
Creates a cached parser instance.
config := &model.CacheConfig{
TTL: 5 * time.Minute,
MaxEntries: 1000,
CleanupInterval: 2 * time.Minute,
}
parser := model.NewCachedParser[User](config)
defer parser.Close()
CachedParser Methods
func (cp *CachedParser[T]) Parse(data []byte) (T, error)
func (cp *CachedParser[T]) ParseWithFormat(data []byte, format Format) (T, error)
func (cp *CachedParser[T]) Stats() (size, maxSize int, hitRate float64)
func (cp *CachedParser[T]) ClearCache()
func (cp *CachedParser[T]) Close()
DefaultCacheConfig
Returns sensible defaults:
- TTL: 1 hour
- MaxEntries: 1000
- CleanupInterval: 30 minutes
Configuration
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)
}
Global Configuration
Package-level configuration variables:
var MaxInputSize = 10 * 1024 * 1024 // Max 10MB input (0 = unlimited)
var MaxCacheSize = 1000 // Max validation metadata cache (0 = unlimited)
var MaxValidationDepth = 32 // Max nested struct depth
var MaxStructureDepth = 64 // Max JSON/YAML nesting depth (0 = unlimited)
Warning: Direct modification of these variables is NOT thread-safe. Use the Get/Set functions for concurrent access.
Thread-Safe Accessors
// MaxInputSize
func GetMaxInputSize() int
func SetMaxInputSize(size int)
// MaxCacheSize
func GetMaxCacheSize() int
func SetMaxCacheSize(size int)
// MaxValidationDepth
func GetMaxValidationDepth() int
func SetMaxValidationDepth(depth int)
// MaxStructureDepth
func GetMaxStructureDepth() int
func SetMaxStructureDepth(depth int)
Example:
// Safe for concurrent use
model.SetMaxInputSize(5 * 1024 * 1024) // 5MB
size := model.GetMaxInputSize()
Sensitive Field Patterns
Configure which field names are considered sensitive for error value sanitization:
// Get current patterns
patterns := model.GetSensitiveFieldPatterns()
// Replace all patterns
model.SetSensitiveFieldPatterns([]string{"password", "secret", "token"})
// Add a pattern
model.AddSensitiveFieldPattern("ssn")
// Check if a field is sensitive
model.IsSensitiveField("user_password") // true
Default patterns: password, passwd, secret, token, key, credential, auth, api_key, apikey, private, bearer
Validation Tags
Built-in Validators
| Tag | Applies To | Description | Example |
|---|---|---|---|
required |
All types | Non-zero value required | validate:"required" |
min=N |
Numbers | Minimum value | validate:"min=1" |
max=N |
Numbers | Maximum value | validate:"max=100" |
min=N |
String, Slice | Minimum length | validate:"min=3" |
max=N |
String, Slice | Maximum length | validate:"max=50" |
length=N |
String | Exact length | validate:"length=8" |
email |
String | Valid email format | validate:"email" |
alpha |
String | Alphabetic only (a-zA-Z) | validate:"alpha" |
alphanum |
String | Alphanumeric only | validate:"alphanum" |
Custom Validators
Cross-field validators (like eqfield, nefield) are not built-in but can be easily added:
model.RegisterGlobalFunc("is_even", func(fieldName string, value interface{}, params map[string]interface{}) error {
num, ok := value.(int)
if !ok {
return nil
}
if num%2 != 0 {
return model.NewValidationError(fieldName, value, "is_even", "must be even")
}
return nil
})
Type Coercion
Automatic conversion between compatible types:
| Target | From | Examples |
|---|---|---|
int |
string, float64 |
"42" → 42, 42.0 → 42 |
float64 |
string, int |
"3.14" → 3.14, 42 → 42.0 |
bool |
string, int |
"true" → true, 1 → true |
string |
Any | 42 → "42", true → "true" |
time.Time |
string, int |
RFC3339, Unix timestamps |
Boolean coercion:
- Truthy:
"true","yes","1","on",1, non-zero - Falsy:
"false","no","0","off","",0
Time formats: RFC3339, RFC3339Nano, Date only (2023-01-15), Unix timestamp (int/float)
Error Types
ParseError
Returned for type coercion failures.
ValidationError
Returned for validation failures.
Multiple Errors
Multiple errors are aggregated:
multiple errors: validation error on field 'ID': field is required; parse error on field 'Age': cannot convert string 'invalid' to integer
Security note: Error messages include field values. Sanitize before logging or returning to clients.
Struct Tags
JSON Tags
type User struct {
ID int `json:"id"`
Name string `json:"name,omitempty"`
Hidden string `json:"-"` // Ignored
}
YAML Tags
type Config struct {
Port int `yaml:"port" json:"port"` // Both formats
Host string `yaml:"host"` // YAML only
}
Falls back to JSON tag if YAML tag is missing.
See Also
- Types Reference - Supported types and limitations
- Migration Guide - Switching from other libraries
- Architecture - Implementation details