25

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.

madshov
  • 653
  • 3
  • 9
  • 15
  • From the docs: "Viper can search multiple paths, but currently a single Viper instance only supports a single configuration file." https://github.com/spf13/viper#reading-config-files – jordanpg Jul 01 '20 at 15:43

1 Answers1

52

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]
svenwltr
  • 17,002
  • 12
  • 56
  • 68
  • What if the configuration file name remains the same between different folders? For example having a global config for your app in your home and then a project specific config in the cwd. The one on your home can be called with a 'global' prefix, but keeping the same name is simpler. – edupo Jul 09 '18 at 06:49
  • @edupo Just change the `ConfigPath` in each time you load a new config file, like the example above. – Justin Nov 03 '18 at 02:16
  • `viper.AddConfigPath` adds to the global search path, it does not replace it. – jordanpg Jul 01 '20 at 15:31
  • sadly, enviper is [incompatible](https://github.com/iamolegga/enviper/blob/master/enviper.go#L51) with this solution – mikhalytch Aug 22 '23 at 11:04