脚本宝典收集整理的这篇文章主要介绍了golang 使用 viper 读取自定义配置文件,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
viPEr 支持 Yaml、Json、 TOML、HCL 等格式,读取非常的方便。
viper 官网有案例:https://github.com/spf13/viper
创建 config.yaml 文件
建一个 config.go 用于初始化配置文件
func InitConfig() { path, err := os.Getwd() if err != nil { panic(err) } viper.AddConfigPath(path + "/config/dev") viper.SetConfigName("config") viper.SetConfigType("yaml") if err := viper.ReadInConfig(); err != nil { panic(err) } }
简单使用:
username := viper.GetString("database.username") password := viper.GetString("database.password") host := viper.GetString("database.host") port := viper.GetInt("database.port") dbname := viper.GetString("database.dbname") dsn := fmt.SPRintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local",username,password,host, port, dbname) GormPool, err = gorm.Open("mySQL", dsn)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本宝典。
以上是脚本宝典为你收集整理的golang 使用 viper 读取自定义配置文件全部内容,希望文章能够帮你解决golang 使用 viper 读取自定义配置文件所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。