$ go run main.goUsing configuration file '/Users/lyre/workspace/misc/go/src/viper/config.yaml'Global.Source: 'config(local)'$ go run main.go --config ./config.yamlUsing configuration file './config.yaml'Global.Source: 'config(local)'
<b> </b>var globalUnset = pflag.String("global.unset", "default(flag)", "this parameter do not appear in config file")func main() { pflag.Parse() viper.BindPFlags(pflag.CommandLine) viper.SetDefault("global.unset", "default(viper)") fmt.Println (viper.GetString("global.unset")) // }
复制代码
· viper.SetDefault()的优先级更高,只要设置了这个,它会忽略pflag的默认值,除非运行时显式指定了命令行参数的值。 · 如果pflag设置了默认值而viper没有,viper取pflag的值。 Remote KV Store
最后,作为对本地配置文件的替代品,viper支持从etcd/consul直接读取配置,以etcd为例:
<b> </b>viper.AddRemoteProvider("etcd", "http://127.0.0.1:4001","/config/hugo.json")viper.SetConfigType("json") // because there is no file extension in a stream of bytes, supported extensions are "json", "toml", "yaml", "yml", "properties", "props", "prop", "env", "dotenv"err := viper.ReadRemoteConfig()
<b> </b>// open a goroutine to watch remote changes forevergo func(){ for { time.Sleep(time.Second * 5) // delay after each request // currently, only tested with etcd support err := runtime_viper.WatchRemoteConfig() if err != nil { log.Errorf("unable to read remote config: %v", err) continue } // unmarshal new config into our runtime config struct. you can also use channel // to implement a signal to notify the system of the changes runtime_viper.Unmarshal(&runtime_conf) }}()
复制代码
Bugfix
如果你启用了go mod,在从etcd读取配置的时候可能会遇到这个错误
<b> </b>panic: codecgen version mismatch: current: 8, need 10. Re-generate file: /Users/lyre/go/pkg/mod/github.com/coreos/etcd@v3.3.10+incompatible/client/keys.generated.go
复制代码
解决办法是:
<b> </b>go get github.com/ugorji/go@v1.1.1go get github.com/ugorji/go/codec@none