03-structs

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

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

  1. Struct Definition - Configuration schema defined as Go structs
  2. Mapstructure Tags - Control how fields map to configuration keys
  3. FromMap - Convert nested maps to flat key-value pairs
  4. Type Safety - Automatic conversion to correct Go types
  5. 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.Nameapp.name
  • Config.Server.Portserver.port
  • Config.Database.MaxConnsdatabase.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

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