Multiple config files with go-viper

madshov picture madshov · Nov 8, 2017 · Viewed 11.1k times · Source

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.

Answer

svenwltr picture svenwltr · Nov 8, 2017

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]