09-key-mapping

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: 3 Imported by: 0

README

Key Mapping Example

This example demonstrates the relationship between configuration keys and struct fields when using Unmarshal.

Key Points

  1. Struct fields use mapstructure tags to define their configuration names
  2. Nested structs create dotted paths - a struct tagged as "server" with a field tagged as "port" creates the path "server.port"
  3. 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:

  1. Examines your struct to extract all field paths using mapstructure tags
  2. For each field path (e.g., "database.primary.host"), it searches all configuration layers
  3. Keys are matched using normalization - dots, underscores, hyphens, and case are all normalized
  4. The value from the highest priority layer (last added) wins
  5. 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!

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