10-validation

command
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2025 License: MIT Imports: 4 Imported by: 0

README

Configuration Validation Example

This example demonstrates validation patterns for confkit. While confkit itself doesn't enforce validation (staying minimal), it provides helpers to make validation easier.

Key Concepts

  1. Unmatched Keys Detection - Find typos and invalid configuration
  2. Custom Validation Rules - Enforce business logic requirements
  3. Source-Specific Validation - Some values should only come from certain sources
  4. Field Dependencies - Required fields, conflicts, and relationships

Validation Helpers

UnmatchedKeys

Detects configuration keys that don't match any struct field:

unmatched := confkit.UnmatchedKeys(cfg, &Config{})
if len(unmatched) > 0 {
    log.Printf("Warning: unknown keys: %v", unmatched)
}

This helps catch:

  • Typos in configuration files
  • Deprecated configuration keys
  • Keys meant for different applications
ValidateRules

Enforces custom validation rules:

rules := []confkit.ValidationRule{
    // Password must come from environment
    {Path: "database.password", Required: true, Sources: []string{"env"}},
    
    // TLS cert and key must be set together
    {Path: "server.tls.cert", RequiredWith: []string{"server.tls.key"}},
    
    // Debug and production modes are mutually exclusive
    {Path: "features.debug", ConflictsWith: []string{"features.production"}},
}

if errs := confkit.ValidateRules(cfg, rules); len(errs) > 0 {
    // Handle validation errors
}

Custom Validation Patterns

Using Struct Tags

While confkit doesn't interpret custom tags, you can use them for validation:

type Config struct {
    Database struct {
        Password string `mapstructure:"password" required:"true" env-only:"true"`
    } `mapstructure:"database"`
}

Then build rules from tags:

fields := confkit.ExtractFields(Config{}, "mapstructure", "required", "env-only")
// Build ValidationRule structs from field tags
Source Restrictions

Some configuration should only come from specific sources:

  • Secrets - Only from environment variables
  • Internal settings - Only from defaults, not user-configurable
  • Feature flags - Only from specific config files
Business Logic Validation

Beyond structural validation:

  • Mutually exclusive features
  • Dependent configuration (if A is set, B must also be set)
  • Value range validation (ports, percentages, etc.)
  • Cross-field validation (start_date < end_date)

Best Practices

  1. Fail Fast - Validate configuration at startup
  2. Clear Messages - Tell users exactly what's wrong
  3. Show Sources - Help users understand where values come from
  4. Warn vs Error - Unknown keys might be warnings, missing required fields are errors
  5. Layer-Specific Validation - Different rules for different sources

Example Output

=== Configuration Validation Demo ===

1. Checking for unmatched configuration keys...
⚠️  Warning: Unknown configuration keys detected:
   - unknown.setting
   - server.invalid
   These keys will be ignored.

2. Building validation rules from struct tags...
✓ Created 7 validation rules

3. Validating configuration...
❌ Validation failed with the following errors:
   - field "server.tls.cert" can only be set from sources [env], but was set from "config.json"
   - field "features.debug" conflicts with "features.production"

4. Configuration sources (for debugging):
   server.host          = 0.0.0.0              (from config.json)
   database.password    = secret123            (from env, original: APP_DATABASE_PASSWORD)
   features.debug       = true                 (from env, original: APP_FEATURES_DEBUG)

This approach keeps confkit simple while enabling sophisticated validation!

Documentation

The Go Gopher

There is no documentation for this package.

Jump to

Keyboard shortcuts

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