在我們做乙個工程化專案的時候,經常涉及到配置檔案的讀取,viper 包很好地滿足這一需求,而且在 golang 生態中是流行度最高的。匯入方式:
這裡分享下我對 viper 包的使用關鍵實踐:import
"github.com/spf13/viper"
接下來在工程入口處引用上面這個配置包的 init 函式做配置檔案的初始化和載入,載入的結果就是例項化乙個 *viper.viper 全域性變數,在其他包中用的時候呼叫這個配置包的 func getconfig() *viper.vipe 函式即可拿到這個全域性變數,即配置檔案內容。
)// viperconfig 全域性配置變數
var viperconfig *viper.viper
// 初始化配置檔案相關設定,在 main 包中呼叫進行初始化載入
func
init
(configdir string
)error
if!fs.
pathexists
(configdir)
viper.
setconfigname
("spider"
)// name of config file (without extension)
viper.
addconfigpath
(configdir)
// path to look for the config file in
err := viper.
readinconfig()
// find and read the config file
if err !=
nil viperconfig = viper.
getviper()
if err =
validateconfig
(viperconfig)
; err !=
nilreturn
nil}
// getconfig 獲取全域性配置
func
getconfig()
*viper.viper
func
validateconfig
(v *viper.viper)
error
if outputdirectory ==
""if maxdepth <=
0if crawlinterval <=
0if crawltimeout <=
0if targeturl ==
""if threadcount <=
0return
nil}
golang讀取配置檔案
在專案中往往將一些配置資訊放到配置檔案中,這樣在不同的執行環境中,只需修改配置檔案即可。以下介紹兩種通過第三方包獲取配置檔案的方式 一 通過gopkg.in ini.v1 go get gopkg.in ini.v11.配置檔案 test.conf mqtt mqtt hostname 127.0....
golang 讀取配置檔案vipper
讀取配置檔案的,有toml和vipper兩種好用的方法,toml的方法見 最大的特點就是要為配置檔案構建相對應的結構體,有點囧,現在講乙個vipper。init 初始化配置 func init v viper.new v.setconfigtype yaml v.setconfigname env ...
Golang讀取配置檔案 ini 資訊
package main import fmt io ioutil regexp strings func checkerr e error 函式名 getcfg tag string,cfg string string 參 數 tag string 引數的名稱 cfg string 配置資訊字串 ...