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)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持靠谱客。
最后
以上就是谦让衬衫最近收集整理的关于golang 使用 viper 读取自定义配置文件的全部内容,更多相关golang内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复