goviper-go

Multiple config files with go-viper


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.


Solution

  • 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: