Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple config files with go-viper

Tags:

go

viper-go

Is it possible to load/merge multiple config files with Viper? Say I have a general config file containing configuration for my program, and client specific config files with configuration for each client, where one of them would be loaded, depending on the input to the program.

Thanks.

like image 688
madshov Avatar asked Nov 08 '17 16:11

madshov


People also ask

What is Viper config?

Viper is a configuration management solution for Go applications which allows you to specify configuration options for your application in several ways, including configuration files, environment variables, and command-line flags.

What is spf13 Viper?

Viper is a complete configuration solution for Go applications including 12-Factor apps. It is designed to work within an application, and can handle all types of configuration needs and formats. It supports: setting defaults. reading from JSON, TOML, YAML, HCL, envfile and Java properties config files.

Why use Viper golang?

Viper is a very popular Golang package for this purpose. It can find, load, and unmarshal values from a config file. It supports many types of files, such as JSON, TOML, YAML, ENV, or INI. It can also read values from environment variables or command-line flags.


Video Answer


1 Answers

viper has ReadInConfig and MergeInConfig, which can called multiple times. Here is an (untested) example:

viper.SetConfigName("default")
viper.AddConfigPath(path)
viper.ReadInConfig()

if context != "" {
    viper.SetConfigName(context)
    viper.AddConfigPath(path)
    viper.MergeInConfig()
}

viper.SetConfigName("config")
viper.AddConfigPath(".")
viper.MergeInConfig()

It reads these files in this order:

  • $path/default.[yaml|toml|json]
  • $path/$context.[yaml|toml|json]
  • ./config.[yaml|toml|json]
like image 152
svenwltr Avatar answered Sep 21 '22 11:09

svenwltr