Go Application Configuration: Viper Library

онлайн тренажер по питону

What is viper and why is it needed?

Viper is a powerful library for Go (Golang) designed for managing application configuration. It supports reading settings from various sources: files (JSON, TOML, YAML, HCL, INI, envfile), environment variables, command-line flags, and remote systems (etcd, Consul). Viper automatically merges all sources, resolving conflicts in favor of higher priority ones (for example, command-line flags have the highest priority). The library allows you to easily manage configuration during application runtime, track file changes, and dynamically reload settings.

Installation

To install viper, run the command:

go get github.com/spf13/viper

Make sure you have Go version 1.18 or higher installed.

Main Features

  • Reading from files: supports JSON, TOML, YAML, HCL, INI, envfile formats.
  • Environment variables: automatic binding with environment variables.
  • Command-line flags: integration with pflag for parsing arguments.
  • Remote configs: support for etcd, Consul, Firestore (via extensions).
  • Change tracking: WatchConfig allows reloading configuration when a file changes.
  • Nested keys: access to hierarchical data via dot notation (e.g., app.port).
  • Default values: set via SetDefault.

Go Code Example

package main

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

func main() {\tviper.SetConfigName("config") // file name without extension\tviper.SetConfigType("yaml") // format\tviper.AddConfigPath(".") // path to file\tviper.AutomaticEnv() // read environment variables

\t// Default values\tviper.SetDefault("app.port", 8080)

\t// Reading configuration\tif err := viper.ReadInConfig(); err != nil {\t\tfmt.Printf("Error reading config: %v", err)\t}

\t// Getting values\tport := viper.GetInt("app.port")\tname := viper.GetString("app.name")

\tfmt.Printf("Server running on port %d, application: %s", port, name)

\t// Example config.yaml file:\t// app:\t// port: 3000\t// name: myapp}

When to use viper

The library is ideal for microservices, web applications, CLI utilities, and any Go projects that require flexible settings management. It is especially useful when configuration must come from multiple sources (file + environment + flags) or when you need to dynamically reload settings without restarting the application. Viper simplifies working with configuration, eliminating the need for manual parsing and data merging.