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)
相关推荐
GoatSucker 2020-11-23
CoderToy 2020-11-16
蛰脚踝的天蝎 2020-11-10
ZGCdemo 2020-11-09
86193952 2020-10-27
Lzs 2020-10-23
hjr 2020-10-21
HELLOBOY 2020-10-21
qidiantianxia 2020-10-21
cmsmdn 2020-10-21
myspace 2020-10-21
笑面依旧 2020-10-21
专注前端开发 2020-10-21
技术之博大精深 2020-10-16
zhushenghan 2020-11-09
风雨断肠人 2020-10-13
xuguiyi00 2020-11-04
sichenglain 2020-10-27