Skip to main content

Viper Configuration

Github StackBlitz

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.yaml automatically 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 mapstructure tags.

Prerequisites​

  • Go 1.26 or newer.

Setup & Running​

  1. Navigate to the recipe directory:
cd viper-config
  1. Run the application:
go run main.go
  1. 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: OK

env and service come from config.yaml, port and version from the defaults in main.go.

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

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