command
Version:
v0.1.2
Opens a new window with list of versions in this module.
Published: Jul 18, 2025
License: MIT
Opens a new window with license information.
Imports: 4
Opens a new window with list of imports.
Imported by: 0
Opens a new window with list of known importers.
README
¶
Example 03: Struct-Based Configuration
Using Go structs to define and load configuration.
What This Shows
- Defining configuration as nested structs
- Using
mapstructure tags for field mapping
- Loading from nested maps with
FromMap
- Unmarshaling to structs with type conversion
- Automatic handling of durations and other types
Running
go run main.go
Key Points
- Struct Definition - Configuration schema defined as Go structs
- Mapstructure Tags - Control how fields map to configuration keys
- FromMap - Convert nested maps to flat key-value pairs
- Type Safety - Automatic conversion to correct Go types
- Nested Structures - Support for complex configuration hierarchies
Type Conversions
The library automatically handles common conversions:
- String "true"/"false" → bool
- String numbers → int, float64
- Duration strings → time.Duration (e.g., "30s", "5m")
- String values → appropriate types based on struct fields
Configuration Keys
The struct fields map to flat keys:
Config.App.Name → app.name
Config.Server.Port → server.port
Config.Database.MaxConns → database.max_conns
Output Example
=== Loaded Configuration ===
App:
Name: MyApplication
Version: 1.0.0
Debug: true
Server:
Host: 0.0.0.0
Port: 9000
Read Timeout: 30s
Write Timeout: 30s
Database:
Host: db.example.com
Port: 5432
Database: myapp
User: appuser
Max Connections: 50
Documentation
¶
There is no documentation for this package.
Source Files
¶
Click to show internal directories.
Click to hide internal directories.