Key Mapping Example
This example demonstrates the relationship between configuration keys and struct fields when using Unmarshal.
Key Points
- Struct fields use mapstructure tags to define their configuration names
- Nested structs create dotted paths - a struct tagged as "server" with a field tagged as "port" creates the path "server.port"
- Key normalization makes formats interchangeable:
- JSON/YAML style:
database.primary.host
- Environment style:
DATABASE_PRIMARY_HOST
- CLI flag style:
database-primary-host
- Mixed styles:
Database.Primary.Host, database_PRIMARY_host
The Mapping Process
When you call cfg.Unmarshal(&config), confkit:
- Examines your struct to extract all field paths using mapstructure tags
- For each field path (e.g., "database.primary.host"), it searches all configuration layers
- Keys are matched using normalization - dots, underscores, hyphens, and case are all normalized
- The value from the highest priority layer (last added) wins
- mapstructure handles type conversion (string → int, string → bool, etc.)
Common Patterns
Environment Variables
// Struct field: Database.Primary.Host
// Mapstructure path: database.primary.host
// Common env var: DATABASE_PRIMARY_HOST
JSON Files
// Struct field: Database.Primary.Host
// Mapstructure path: database.primary.host
// JSON key: "database.primary.host" or nested objects
CLI Flags
// Struct field: Database.Primary.Host
// Mapstructure path: database.primary.host
// CLI flag: --database-primary-host
All three formats map to the same struct field!