golang 使用 viper 讀取自定義配置文件
viper 支持 Yaml、Json、 TOML、HCL 等格式,讀取非常的方便。
viper 官網(wǎng)有案例:https://github.com/spf13/viper
go get github.com/spf13/viper
創(chuàng)建 config.yaml 文件
database: driver: mysql host: 127.0.0.1 port: 3306 username: blog dbname: blog password: 123456
建一個(gè) 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)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
手把手教你如何在Goland中創(chuàng)建和運(yùn)行項(xiàng)目
歡迎來到本指南!我們將手把手地教您在Goland中如何創(chuàng)建、配置并運(yùn)行項(xiàng)目,通過簡單的步驟,您將迅速上手這款強(qiáng)大的集成開發(fā)環(huán)境(IDE),輕松實(shí)現(xiàn)您的編程夢想,讓我們一起開啟這段精彩的旅程吧!2024-02-02Golang中數(shù)據(jù)結(jié)構(gòu)Queue的實(shí)現(xiàn)方法詳解
這篇文章主要給大家介紹了關(guān)于Golang中數(shù)據(jù)結(jié)構(gòu)Queue的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-09-09Go語言開發(fā)編程規(guī)范命令風(fēng)格代碼格式
這篇文章主要為大家介紹了Go語言開發(fā)編程規(guī)范命令風(fēng)格代碼格式,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06一百行Golang代碼實(shí)現(xiàn)簡單并發(fā)聊天室
這篇文章主要為大家詳細(xì)介紹了一百行Golang代碼如何實(shí)現(xiàn)簡單并發(fā)聊天室,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-08-08