recipes/viper-config
Viper Configuration
Manage layered application configuration in Fiber using Viper with YAML and environment variables.
This recipe demonstrates how to manage layered configurations in a Fiber application using Viper.
Features
- Layered Defaults: Pre-configured defaults for application settings.
- YAML Configuration File: Reads
config.yamlautomatically when present. - Environment Variable Overrides: Environment variables prefixed with
APP_override file and default values. - Type-safe Unmarshaling: Maps configuration values directly into a Go struct with
mapstructuretags.
Prerequisites
- Go 1.27 or newer.
Setup & Running
- Navigate to the recipe directory:
cd viper-config- Run the application:
go run main.go- In a separate terminal, test the endpoints:
curl http://localhost:3000/
# Output: {"env":"staging","port":3000,"service":"Fiber Viper (from config.yaml)","version":"1.0.0"}
curl http://localhost:3000/healthz
# Output: OKenv and service come from config.yaml, port and version from the defaults in main.go.
- Test overriding settings with environment variables:
Stop the running server (Ctrl+C), then start with custom environment variables:
APP_PORT=8080 APP_ENV=production APP_SERVICE_NAME="Fiber Production" go run main.goIn a separate terminal:
curl http://localhost:8080/
# Output: {"env":"production","port":8080,"service":"Fiber Production","version":"1.0.0"}Viper's Unmarshal only sees environment values for keys it already knows, which is why every key in loadConfig has a default.