詳解Golang如何動(dòng)態(tài)獲取配置文件
項(xiàng)目中經(jīng)常獲取一些常用配置文件,當(dāng)有配置文件中的參數(shù)被修改后,如何的實(shí)時(shí)獲取配置文件就很關(guān)鍵了。這里推薦"viper"這個(gè)包,用來實(shí)時(shí)獲取配置文件。
1.VIPER簡介
viper【蝰蛇】
Viper是適用于Go應(yīng)用程序的完整配置解決方案。它旨在在應(yīng)用程序中工作,并且可以處理所有類型的配置需求和格式。它支持:
- 設(shè)置默認(rèn)值
- 從JSON,TOML,YAML,HCL,envfile和Java屬性配置文件中讀取
- 實(shí)時(shí)觀看和重新讀取配置文件(可選)
- 從環(huán)境變量中讀取
- 從遠(yuǎn)程配置系統(tǒng)(etcd或Consul)中讀取,并觀察更改
- 從命令行標(biāo)志讀取
- 從緩沖區(qū)讀取
- 設(shè)置顯式值
可以將Viper視為滿足您所有應(yīng)用程序配置需求的注冊表。
2.使用說明
本文中的實(shí)例都是從viper的官方介紹中復(fù)制過來,只是介紹了簡單的使用。完整的實(shí)例請(qǐng)查看【https://pkg.go.dev/github.com...】
2.1建立默認(rèn)值
viper.SetDefault("ContentDir", "content") viper.SetDefault("LayoutDir", "layouts") viper.SetDefault("Taxonomies", map[string]string{"tag": "tags", "category": "categories"})
2.2讀取配置文件
viper.SetConfigName("config") // name of config file (without extension) viper.SetConfigType("yaml") // REQUIRED if the config file does not have the extension in the name viper.AddConfigPath("/etc/appname/") // path to look for the config file in viper.AddConfigPath("$HOME/.appname") // call multiple times to add many search paths viper.AddConfigPath(".") // optionally look for config in the working directory err := viper.ReadInConfig() // Find and read the config file if err != nil { // Handle errors reading the config file panic(fmt.Errorf("Fatal error config file: %s \n", err)) }
2.3 讀取和重新讀取配置文件
viper.WatchConfig() viper.OnConfigChange(func(e fsnotify.Event) { fmt.Println("Config file changed:", e.Name) })
2.4 獲取值
在Viper中,根據(jù)值的類型,有幾種獲取值的方法。存在以下功能和方法:
Get(key string) : interface{}
GetBool(key string) : bool
GetFloat64(key string) : float64
GetInt(key string) : int
GetIntSlice(key string) : []int
GetString(key string) : string
GetStringMap(key string) : map[string]interface{}
GetStringMapString(key string) : map[string]string
GetStringSlice(key string) : []string
GetTime(key string) : time.Time
GetDuration(key string) : time.Duration
IsSet(key string) : bool
AllSettings() : map[string]interface{}
3. 實(shí)例代碼
使用GIN框架,簡單配置一個(gè)可以通過接口獲取配置內(nèi)容的http服務(wù)。當(dāng)調(diào)用接口http://127.0.0.1:8080/getConfig可以獲取配置項(xiàng)
步驟1:設(shè)置配置文件
在工作目錄中創(chuàng)建config.yml文件,文件內(nèi)容如下:
Version: "2.1" Debug: false MongoDB: IP: 127.0.0.1 Port: 27017 DbName: "db_name"
步驟二:編寫服務(wù)代碼
package main import ( "fmt" "github.com/fsnotify/fsnotify" "github.com/gin-gonic/gin" "github.com/spf13/viper" ) var config *viper.Viper func main() { config = initConfigure() r := gin.Default() r.GET("/getConfig", func(c *gin.Context) { c.JSON(200, gin.H{ "config": config.AllSettings(), }) }) r.Run() // listen and serve on 0.0.0.0:8080 } func initConfigure() *viper.Viper { v := viper.New() v.SetConfigName("config") // 設(shè)置文件名稱(無后綴) v.SetConfigType("yaml") // 設(shè)置后綴名 {"1.6以后的版本可以不設(shè)置該后綴"} v.AddConfigPath("./") // 設(shè)置文件所在路徑 v.Set("verbose", true) // 設(shè)置默認(rèn)參數(shù) if err := v.ReadInConfig(); err != nil { if _, ok := err.(viper.ConfigFileNotFoundError); ok { panic(" Config file not found; ignore error if desired") } else { panic("Config file was found but another error was produced") } } // 監(jiān)控配置和重新獲取配置 v.WatchConfig() v.OnConfigChange(func(e fsnotify.Event) { fmt.Println("Config file changed:", e.Name) }) return v }
步驟三:演示:
啟動(dòng)服務(wù),通過postman調(diào)用http://127.0.0.1:8080/getConfig 可以獲得如下參數(shù):
這個(gè)時(shí)候把yml文件中的version修改成3.0。這個(gè)時(shí)候后臺(tái)會(huì)打印輸出一句
Config file changed: /Users/Keil/GoLang/src/tutorials/viper/config.yml
這是因?yàn)槲以诖a中調(diào)用了兩個(gè)關(guān)鍵的函數(shù),WatchConfig和OnConfigChange。函數(shù)OnConfigChange打印輸出了這句,輸出代碼:fmt.Println("Config file changed:", e.Name)
關(guān)于這兩個(gè)函數(shù)的源碼解析和工作原理,可以參考【go基于viper實(shí)現(xiàn)配置文件熱更新及其源碼分析】。里面介紹的比較詳細(xì)。這里只是介紹如何使用。
此時(shí)再次調(diào)用接口,配置信息會(huì)變成如下:
4.資料鏈接
go基于viper實(shí)現(xiàn)配置文件熱更新及其源碼分析
到此這篇關(guān)于詳解Golang如何動(dòng)態(tài)獲取配置文件的文章就介紹到這了,更多相關(guān)Go配置文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
一文弄懂用Go實(shí)現(xiàn)MCP服務(wù)的示例代碼
本文主要介紹了一文弄懂用Go實(shí)現(xiàn)MCP服務(wù)的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-04-04Go語言使用net/http實(shí)現(xiàn)簡單登錄驗(yàn)證和文件上傳功能
這篇文章主要介紹了Go語言使用net/http實(shí)現(xiàn)簡單登錄驗(yàn)證和文件上傳功能,使用net/http模塊編寫了一個(gè)簡單的登錄驗(yàn)證和文件上傳的功能,在此做個(gè)簡單記錄,需要的朋友可以參考下2023-07-07go數(shù)據(jù)結(jié)構(gòu)和算法BitMap原理及實(shí)現(xiàn)示例
這篇文章主要為大家介紹了go數(shù)據(jù)結(jié)構(gòu)和算法BitMap原理及實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07