Guide · Open source
How to use Viper: read config files, env vars and flags in Go
Updated · written with AI from the project's own documentation and checked against our catalogue data
Viper is an open-source Go library that reads a program's settings from several places at once, including config files, environment variables, command-line flags and remote key-value stores. This guide shows how to install it, load a config file, bind environment variables and flags, and understand which source wins when the same setting appears in more than one place. It is written for developers who already write Go and want one place to read configuration from.
Quick start
- 1Install the library. Run go get github.com/spf13/viper inside a Go module.
- 2Set the config name and paths. Call SetConfigName and add one or more AddConfigPath locations.
- 3Read the config file. Call ReadInConfig and handle any error it returns.
- 4Bind environment variables. Use SetEnvPrefix with BindEnv or AutomaticEnv to read matching environment variables.
- 5Bind a flag. Define a flag with pflag or Cobra, then tie it to a key with BindPFlag.
- 6Read values. Call viper.Get or a typed getter such as GetBool, which applies the precedence order.
Install Viper in a Go module
Viper is installed as a library into a Go module. It uses Go Modules to manage its dependencies, and the project's badge indicates Go 1.23 or newer.
- Make sure you have Go installed, version 1.23 or newer.
- Run the install command from inside your Go module.
go get github.com/spf13/viperLoad a config file with Viper
Viper supports JSON, TOML, YAML, INI, envfile and Java Properties files. Set the config name without an extension, add one or more search paths, then call ReadInConfig. Viper works out the file type from the extension. A single Viper instance supports one config file, but it can search several paths for it.
If you need to tell a missing file apart from a broken one, check the error with errors.As against viper.FileLookupError.
- Supported formats: JSON, TOML, YAML, INI, envfile, Java Properties.
- One Viper instance reads one config file, found through any of the search paths you add.
- Files without an extension can be used if you specify the format in code.
viper.SetConfigName("config")
viper.AddConfigPath("/etc/appname/")
viper.AddConfigPath("$HOME/.appname")
viper.AddConfigPath(".")
err := viper.ReadInConfig()
if err != nil {
panic(fmt.Errorf("fatal error config file: %w", err))
}Understand the precedence order
Viper merges all sources into one set of keys. When the same key is set in several places, the source higher in this list wins. Configuration keys are case insensitive. Defaults are the lowest priority.
- Explicit call to Set
- Flags
- Environment variables
- Config files
- External key/value stores
- Defaults
Read environment variables and flags
Viper can read environment variables with a prefix, bind single keys with BindEnv, or load all matching variables with AutomaticEnv. Unlike other sources, environment variables are case sensitive. Viper reads them each time they are accessed rather than caching them.
For command-line flags, Viper supports pflag, the flag library used by Cobra. Use BindPFlag to tie one flag to a key. The flag's value is read when accessed, not when the binding is made.
- Empty environment variables count as unset unless AllowEmptyEnv is used.
- SetEnvKeyReplacer and EnvKeyReplacer rewrite environment variable keys.
- You can also bind a whole set of pflags at once.
viper.SetEnvPrefix("spf")
viper.BindEnv("id")
viper.AutomaticEnv()
serverCmd.Flags().Int("port", 1138, "Port to run Application server on")
viper.BindPFlag("port", serverCmd.Flags().Lookup("port"))Set defaults, overrides and aliases
Defaults apply when a key is not set anywhere else. Set overrides from your own code with Set, which has the highest priority. Aliases let one value be read under several keys.
- SetDefault sets a fallback value.
- Set overrides any other source.
- RegisterAlias makes two keys refer to the same value.
viper.SetDefault("ContentDir", "content")
viper.Set("verbose", true)
viper.RegisterAlias("loud", "Verbose")
viper.GetBool("loud") // trueReload config while the program runs
Viper can watch a config file and re-read it while the application is running, so you do not have to restart the server for changes to take effect. Register a function with OnConfigChange to run each time the file changes. Define all config paths before calling WatchConfig.
viper.AddConfigPath("$HOME/.appname")
viper.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("Config file changed:", e.Name)
})
viper.WatchConfig()What people use it for
- A command-line tool that reads a port from a flag, a token from an environment variable, and other defaults from a file.
- A server that reloads its settings while running after the config file is edited.
- A Go service that follows the 12-factor approach by reading settings from environment variables.
- A Cobra-based CLI where flags and config file values are merged under one set of keys.
Frequently asked questions
Is Viper free to use?
Viper is released under the MIT licence, as listed in the project details. The MIT licence permits use in other projects, but check the licence text itself before relying on it for a commercial product.
What do I need to use Viper?
You need Go, and the project badge indicates Go 1.23 or newer. You install Viper into a Go module with go get github.com/spf13/viper, since it uses Go Modules to manage dependencies.
Can Viper read a .env file?
Viper lists envfile among the config file formats it supports. Its README does not describe a separate dotenv-specific feature, so check the project documentation for details before depending on that behaviour.
Which takes priority, a flag or an environment variable?
Flags take priority over environment variables. The full order is an explicit Set call, then flags, then environment variables, then config files, then external key/value stores, then defaults.
Does Viper work with Cobra?
Yes. Viper supports pflag, the flag library used by Cobra, and you can bind a Cobra command's flag with BindPFlag so it shares the same config.
What are the alternatives to Viper?
The project's comparison list names koanf, envconfig, godotenv and Cobra. Cobra is a command-line framework, so it works alongside configuration libraries rather than replacing them. Viper suits projects that need many sources in one place, while very small programs may only need one file or a few environment variables.
New agent skills, repos and AI tools — every week
The best new skills and open-source projects, the fastest-growing repos, and one free prompt. Five minutes to read. Unsubscribe anytime.
Our verdict
Viper suits Go developers building command-line tools or servers that must merge settings from files, environment variables and flags, especially if they use Cobra or pflag. It is a Go-only library, so non-Go projects should look elsewhere. For a program that reads one file or a handful of environment variables, the added dependency and concepts may not be worth it.
Install options & downloads