GitHub: GoLang/viper_config
Viper Configuration Example
A demonstration of using Viper for application configuration management in Go. This example shows how to read configuration from YAML files and override values with environment variables.
Features
- π YAML Configuration: Read configuration from
config.yaml - π§ Environment Variable Override: Environment variables automatically override config file values
- ποΈ Structured Config: Type-safe configuration using Go structs
- π Automatic Env Mapping: Dot notation in config maps to underscore in env vars (
server.portβSERVER_PORT)
Configuration Structure
server:
host: localhost
port: 8080
timeout: 10s
Maps to Go struct:
type Config struct {
Server struct {
Host string
Port int
Timeout time.Duration
}
}
Usage
Run with default config
go run .
Output:
Server: localhost:8080
Timeout: 10s
Override with environment variables
# Override port using environment variable
export SERVER_PORT=9000
go run .
Output:
Server: localhost:9000
Timeout: 10s
Override multiple values
export SERVER_HOST=0.0.0.0
export SERVER_PORT=3000
export SERVER_TIMEOUT=30s
go run .
Output:
Server: 0.0.0.0:3000
Timeout: 30s
Key Features of Viper
1. Automatic Environment Variable Mapping
viper.AutomaticEnv()
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
This allows server.port in config to be overridden by SERVER_PORT environment variable.
2. Type-Safe Configuration
var config Config
err = viper.Unmarshal(&config)
Viper automatically unmarshals the configuration into strongly-typed Go structs, including parsing durations like 10s into time.Duration.
3. Multiple Configuration Sources
Viper supports reading from:
- Configuration files (YAML, JSON, TOML, etc.)
- Environment variables
- Command-line flags
- Remote config systems (etcd, Consul)
File Structure
viper_config/
βββ config.go # Configuration setup and struct definition
βββ config.yaml # Default configuration file
βββ main.go # Example usage
Why Use Viper?
β
12-Factor App Compliant: Separate config from code
β
Flexible: Multiple config sources with priority order
β
Type-Safe: Strong typing with automatic unmarshaling
β
Production-Ready: Used by many popular Go projects
β
Easy Testing: Override config for different environments
Common Use Cases
- Application server configuration (host, port, timeouts)
- Database connection strings
- Feature flags
- API keys and secrets (combined with secure vaults)
- Multi-environment configuration (dev, staging, prod)
Dependencies
go get github.com/spf13/viper
Learn More
Recent changes
-
2026-01-01 5d1a484 Add outgoing HTTP rate limiter with burst support -
2024-02-10 1e96190 added viper config
Categories: experiments, Go
Tags: golang
← Previous Β· Next →