| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131 |
- package main
- import (
- "fmt"
- "github.com/spf13/pflag"
- "github.com/spf13/viper"
- "log"
- )
- //
- //type songInfo struct {
- // Name string
- // Duration int
- //}
- //
- //type dataBase struct {
- // Server string
- // Ports []int
- //}
- //
- //type servers struct {
- // Alpha server //注意Alpha等首字母大写
- // Beta server
- //}
- //
- //type server struct {
- // Ip string
- // Dc string
- //}
- //
- //type clients struct {
- // Data [][]interface{}
- //}
- //
- //type config struct {
- // Bc string
- // Song songInfo
- // Database dataBase
- // Servers servers
- // Clients clients
- //}
- //
- ////单例模式
- //var (
- // cfg *config
- // once sync.Once
- //)
- //
- //func Config() *config {
- // once.Do(func() {
- // filePath, err := filepath.Abs("./ch3/config.toml")
- // if err != nil {
- // panic(err)
- // }
- // fmt.Printf("parse toml file once. filePath: %s\n", filePath)
- // if _, err := toml.DecodeFile(filePath, &cfg); err != nil {
- // panic(err)
- // }
- // })
- // return cfg
- //}
- //绑定命令行
- func init() {
- pflag.String("cmd", "cmd", "")
- viper.BindPFlags(pflag.CommandLine)
- }
- /*
- 调用Set显示设置的;
- 命令行选项;
- 环境变量;
- 配置文件;
- 默认值。
- */
- func main() {
- pflag.Parse()
- //var cg config
- //cpath := "./example.toml"
- //if _,err := toml.DecodeFile(cpath,&cg);err != nil {
- // log.Fatal(err)
- //}
- //fmt.Printf("%v %v\n",cg.Bc,cg.Song.Name)
- //fmt.Printf("%v %v\n",cg.Database.Server,cg.Database.Ports[2])
- //fmt.Printf("%v %v\n",cg.Servers.Alpha.Dc,cg.Servers.Beta.Ip)
- //fmt.Printf("%v %v\n",cg.Clients.Data[0][0],cg.Clients.Data[1][0])
- viper.SetConfigName("example")
- viper.SetConfigType("toml")
- viper.AddConfigPath(".")
- if err := viper.ReadInConfig(); err != nil {
- log.Fatalf("read config failed: %v", err)
- }
- fmt.Println(viper.Get("Bc"))
- fmt.Println(viper.Get("song.Name"))
- ports := viper.GetIntSlice("database.ports")
- fmt.Println(ports[2])
- fmt.Println("port", viper.GetIntSlice("database.ports")[0])
- //servers:= viper.GetStringMapString()
- fmt.Println("servers.alpha.ip", viper.GetString("servers.alpha.ip"))
- clients := viper.GetStringMap("clients")
- for _, v := range clients {
- fmt.Println(v)
- for _, j := range v.([]interface{}) {
- fmt.Println(j)
- for _, k := range j.([]interface{}) {
- fmt.Println(k)
- }
- }
- }
- fmt.Println("all settings: ", viper.AllSettings())
- //绑定环境变量
- viper.AutomaticEnv()
- fmt.Println("GOPATH: ", viper.Get("GOPATH"))
- fmt.Println("cmd-line: ", viper.Get("cmd"))
- viper.SetDefault("appversion", "0.0.1")
- fmt.Println("appversion", viper.Get("appversion"))
- }
|