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: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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.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

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