這是第二次實操viper了,linux
年紀大了就多練練,才能記住。git
http://go.coder55.com/article/6589github
https://github.com/spf13/vipergolang
package main import ( "github.com/spf13/pflag" "github.com/spf13/viper" "golang.org/x/net/context" "github.com/fsnotify/fsnotify" "fmt" ) func main() { //讀取Command Line參數 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"), ) //讀取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"), ) //監聽函數,能夠免重啓修改配置參數 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() //反序列化 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) { var yamlObj YamlSetting if err := v.Unmarshal(&yamlObj); err != nil { fmt.Printf("err: %s\n", err) } fmt.Println(yamlObj) }
輸出的樣子api
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中使用pflag並不排除使用 標準庫中使用標誌包的其餘包。pflag包能夠經過導入這些標誌來處理爲標誌包定義的標誌。這是經過調用名爲AddGoFlagSet()的pflag包提供的便利函數來實現的。函數