golang 使用 viper 读取自定义配置文件
更新时间:2020年01月13日 10:59:47 作者:代码的坏味道
这篇文章主要介绍了golang 使用 viper 读取自定义配置文件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
viper 支持 Yaml、Json、 TOML、HCL 等格式,读取非常的方便。
viper 官网有案例:https://github.com/spf13/viper
go get github.com/spf13/viper
创建 config.yaml 文件
database: driver: mysql host: 127.0.0.1 port: 3306 username: blog dbname: blog password: 123456
建一个 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)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
gorm update传入struct对象,零值字段不更新的解决方案
这篇文章主要介绍了gorm update传入struct对象,零值字段不更新的解决方案,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2021-04-04
最新评论