This is the second practical operation of the viper,
Older, the more we thought to keep in mind.
http://go.coder55.com/article/6589
https://github.com/spf13/viper
package main import ( "github.com/spf13/pflag" "github.com/spf13/viper" "golang.org/x/net/context" "github.com/fsnotify/fsnotify" "fmt" ) func main() { // read Command Line Parameters pflag.String("hostAddress", "127.0.0.1", "Server running address") pflag.Int64("port", 8080, "Server running port") pflag.Parse() viper.BindPFlags(pflag.CommandLine) fmt.Printf("hostAddress: %s, port: %s \n", viper.GetString("hostAddress"), viper.GetString("port"), ) // Read file yaml v: = viper.New () v.SetConfigName("linux_config") v.AddConfigPath("./") v.SetConfigType("yaml") if err := v.ReadInConfig(); err != nil { fmt.Printf("err: %s\n", err) } fmt.Printf(`TimeStamp:%s \n CompanyInfomation.Name:%s \n CompanyInfomation.Department:%s \n`, v.Get("TimeStamp"), v.Get("CompanyInfomation.Name"), v.Get("CompanyInfomation.Department"), ) // Listen function, you can avoid restarting modify the configuration parameters ctx, _ := context.WithCancel(context.Background()) v.OnConfigChange(func(e fsnotify.Event) { fmt.Printf("config is change: %s\n", e.String()) fmt.Printf(`TimeStamp:%s \n CompanyInfomation.Name:%s \n CompanyInfomation.Department:%s \n`, v.Get("TimeStamp"), v.Get("CompanyInfomation.Name"), v.Get("CompanyInfomation.Department"), ) }) v.WatchConfig() <-ctx.Done() // deserialize parseYaml (v) } type CompanyInfomation struct { Name string MarketCapitalization int64 EmployeeNum int64 Department []interface{} IsOpen bool } type YamlSetting struct { TimeStamp string Address string Postcode int64 CompanyInfomation CompanyInfomation } func parseYaml(v *viper.Viper) { was yamlObj YamlSetting if err := v.Unmarshal(&yamlObj); err != nil { fmt.Printf("err: %s\n", err) } fmt.Println(yamlObj) }
The output looks like
package main import ( "flag" "github.com/spf13/pflag" ) func main() { // using standard library "flag" package flag.Int("flagname", 1234, "help message for flagname") pflag.CommandLine.AddGoFlagSet(flag.CommandLine) pflag.Parse() viper.BindPFlags(pflag.CommandLine) i := viper.GetInt("flagname") // retrieve value from viper ... }
Viper in the pflag does not preclude the use of standard library use flag other packages packages. pflag packet may be treated as a symbol mark packets defined by introducing these flags. This is accomplished by calling the function pflag convenience package called AddGoFlagSet () is provided.