Multiple config files with go-viper

Viewed 13366

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.

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]
Related