ZhangZhihui's Blog  

 

 

Viper uses github.com/mitchellh/mapstructure under the hood for unmarshaling values which uses mapstructure tags by default.

 

supported extensions are "json", "toml", "yaml", "yml", "properties", "props", "prop", "env", "dotenv"

 

Example:

package util

import "github.com/spf13/viper"

// Config stores all configuration of the application.
type Config struct {
    Environment       string `mapstructure:"ENVIRONMENT"`
    DBSource          string `mapstructure:"DB_SOURCE"`
    HTTPServerAddress string `mapstructure:"HTTP_SERVER_ADDRESS"`
}

// LoadConfig reads configuration from file or environment variables.
func LoadConfig(path string) (config Config, err error) {
    viper.AddConfigPath(path)
    viper.SetConfigName("app")
    viper.SetConfigType("env")

    viper.AutomaticEnv()

    err = viper.ReadInConfig()
    if err != nil {
        return
    }

    err = viper.Unmarshal(&config)
    return
}

 

 

Read multiple config files:

// LoadConfig reads configuration from files or environment variables.
func LoadConfig(path string) (config Config, err error) {
    viper.AddConfigPath(path)
    viper.SetConfigType("env")

    viper.SetConfigName("app")
    err = viper.ReadInConfig()
    if err != nil {
        return
    }

    viper.SetConfigName("app_prod_overwrite")
    err = viper.MergeInConfig() // ReadInConfig() again does not work
    if err != nil {
        return
    }

    viper.AutomaticEnv()    

    err = viper.Unmarshal(&config)
    return
}

 

posted on 2023-12-04 13:38  ZhangZhihuiAAA  阅读(29)  评论(0编辑  收藏  举报