Go Application Configuration: The Viper Library

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is viper and why is it needed?

Viper is a powerful library for configuration management in Go (Golang) applications. It solves one of the key development tasks: centralized and flexible management of application settings, regardless of the data source. Viper supports working with JSON, TOML, YAML, HCL, INI, envfile and environment variables, making it an ideal choice for microservices, CLI utilities, and web applications.

Key Features

  • Multiple sources: reading from files (JSON, YAML, TOML), environment variables, remote stores (etcd, Consul) and even command-line flags.
  • Priorities: automatic conflict resolution — the last set source has the highest priority.
  • Live reloading: ability to watch for changes in configuration files without restarting the application (requires additional setup).
  • Nested key support: access to settings via dot notation (e.g., app.db.host).

Installation

Install viper via the standard Go package manager:

go get github.com/spf13/viper

Go Code Example

Create a file config.yaml:

app:  name: "MyApp"  port: 8080database:  host: "localhost"  user: "admin"  password: "secret"

Example of using viper to read configuration:

package main

import (\t"fmt"\t"github.com/spf13/viper")

func main() {\tviper.SetConfigName("config")\tviper.SetConfigType("yaml")\tviper.AddConfigPath(".")

\terr := viper.ReadInConfig()\tif err != nil {\t\tpanic(fmt.Errorf("error reading configuration: %w", err))\t}

\tappName := viper.GetString("app.name")\tport := viper.GetInt("app.port")\tdbHost := viper.GetString("database.host")

\tfmt.Printf("App: %s, Port: %d, DB: %s", appName, port, dbHost)}

You can also use environment variables with a prefix:

viper.SetEnvPrefix("MYAPP")viper.AutomaticEnv()// Now the MYAPP_APP_PORT environment variable will be accessible as app.port

When to use viper?

  • When support for multiple configuration formats (YAML, JSON, TOML) is required.
  • For applications where settings can be overridden by environment variables (e.g., in Docker/Kubernetes).
  • In a microservice architecture, where configuration can be loaded from external services (etcd, Consul).
  • If you need to separate configuration for dev/staging/production environments.

Viper is the de facto standard for configuration management in the Go community, used in projects such as Hugo, Docker CLI, and many others.

Recommendations