// 首先声明一个配置映射对象type DB struct {host stringport string}func main() {viper.SetConfigName("config")viper.SetConfigType("yaml")viper.AddConfigPath(".")viper.ReadInConfig() // 读取配置var mysql DBviper.Unmarshal(&mysql) 将读取到的配置序列化为对象fmt.Println(mysql.host)fmt.Println(...
ServiceNamestring`mapstructure:"name"`Portint`mapstructure:"port"`}funcmain(){ v := viper.New()//v.SetConfigName("config.yaml")//v.SetConfigType("yaml")//v.AddConfigPath("./")// 文件的路径如何设置v.SetConfigFile("config.yaml")// 这一行跟上面三行功能实现相同err := v.ReadInConfig...
viper.AddSecureRemoteProvider("etcd","http://127.0.0.1:4001","/config/hugo.json","/etc/secrets/mykeyring.gpg")viper.SetConfigType("json") // because there is no file extension in a stream of bytes, supported extensions are "json", "toml", "yaml", "yml", "properties", "props", ...
viper.WriteConfig() // 将当前配置写入“viper.AddConfigPath()”和“viper.SetConfigName”设置的预定义路径 viper.SafeWriteConfig() viper.WriteConfigAs("/path/to/my/.config") viper.SafeWriteConfigAs("/path/to/my/.config") // 因为该配置文件写入过,所以会报错 viper.SafeWriteConfigAs("/path/to...
Hoststring}`mapstructure:"db"`} funcmain(){// 指定要读取的配置文件viper.SetConfigType("yaml")// 指定文件格式viper.SetConfigName("test")// 文件名不用加后缀viper.AddConfigPath(".")// 路径// 设置环境变量读取viper.AutomaticEnv()// 设置环境变量前缀,有这个前缀的环境变量才会读取 _连接viper.Se...
viper.WatchConfig() // 当配置变化之后,做一个回调函数 viper.OnConfigChange(func(e fsnotify.Event) { fmt.Println("config file changed:", e.Name) }) r := gin.Default() r.GET("/version",func(c *gin.Context) { c.String(http.StatusOK, viper.GetString("version")) ...
前面我们都是将map[string]interface{}解码到 Go 结构体中。mapstructure当然也可以将 Go 结构体反向解码为map[string]interface{}。在反向解码时,我们可以为某些字段设置mapstructure:",omitempty"。这样当这些字段为默认值时,就不会出现在结构的map[string]interface{}中:...
默认情况下,mapstructure使用结构体中字段的名称做这个映射 type Mysql struct {Host string `mapstructure:"host"`Port string `mapstructure:"port"`Username string `mapstructure:"username"`Password string `mapstructure:"password"`Method string `mapstructure:"method"`Database string `mapstructure:"database"`Con...
Hoststring`mapstructure:"host"`Passwordstring`mapstructure:"password"`Portint`mapstructure:"port"`DBint`mapstructure:"db"`PoolSizeint`mapstructure:"pool_size"`MinIdleConnsint`mapstructure:"min_idle_conns"`} 然后就是使用viper进行读取 viper.SetConfigFile("config配置文件绝对路径") ...
Viper是一个方便Go语言应用程序处理配置信息的库。它可以处理多种格式的配置。它支持的特性: 设置默认值 从JSON、TOML、YAML、HCL和Java properties文件中读取配置数据 可以监视配置文件的变动、重新读取配置文件 从环境变量中读取配置数据 从远端配置系统中读取数据,并监视它们(比如etcd、Consul) ...