一.下载包
go get github.com/spf13/viper
二.源码
1 func LoadConf(fpname string) { 2 ini := viper.New() 3 ini.SetConfigFile(fpname) 4 5 ini.SetDefault("database.dbname", "esaletest") 6 ini.SetDefault("database.dbhost", "127.0.0.1") 7 ini.SetDefault("database.dbuser", "sa") 8 ini.SetDefault("database.dbpasswd", "Quartz!DockerP4ss") 9 ini.SetDefault("database.dbport", "1433") 10 11 _, err := os.Stat(fpname) 12 if err != nil { 13 if os.IsNotExist(err) { 14 absfpname, _ := filepath.Abs(fpname) 15 os.MkdirAll(filepath.Dir(absfpname), 0755) 16 err := ini.SafeWriteConfigAs(fpname) 17 if err != nil { 18 errs := fmt.Sprintf(`"%s"生成配置文件失败。%s`, fpname, err.Error()) 19 panic(errors.New(errs)) 20 } 21 errs := fmt.Sprintf(`"%s"获取配置不存在!已经重新生成配置文件。`, fpname) 22 panic(errors.New(errs)) 23 } 24 panic(err) 25 } 26 27 /** 28 // 监听到文件变化后的回调 29 ini.OnConfigChange(func(e fsnotify.Event) { 30 fmt.Println("Config file changed:", e.Name) 31 fmt.Println(ini.Get("db.redis.passwd")) 32 }) 33 **/ 34 35 } 36 37 func TestConf() { 38 fpname := "./Conf/a/conf.yml" 39 fmt.Println(path.Ext(fpname)) // .yml 40 fmt.Println(path.Base(fpname)) // conf.yml 41 fmt.Println(path.Dir(fpname)) // Conf/a 42 fmt.Println(filepath.Abs(fpname)) // /home/chad/下载/gospace/gindir/Conf/a/conf.yml <nil> 43 aa, _ := filepath.Abs(fpname) 44 fmt.Println(path.Dir(aa)) // /home/chad/下载/gospace/gindir/Conf/a 45 LoadConf(fpname) 46 }
标签:err,配置文件,更变,fmt,Golang,fpname,ini,Println,SetDefault From: https://www.cnblogs.com/watermeloncode/p/17904802.html