golang配置文件解析器之goconfig框架的使用詳解
每個項目中都會有配置文件管理來管理,比如數(shù)據(jù)庫的配置。
配置文件框架 一般大致思路都是加載配置文件,返回配置操作對象,該對象提供獲取配置api
下面我們來使用goconfig框架來了解配置框架,它解析的是ini文件,ini文件以簡單的文字和結(jié)構組成,一般windows系統(tǒng)比較常見,很多應用程序也會因為其簡單而使用其作為配置文件
官網(wǎng)star目前599
安裝
go get github.com/Unknwon/goconfig
配置示例
在項目下建立一個文件 conf/conf_goconfig.ini 內(nèi)容如下
[mysql] host = 127.0.0.1 port = 3306 ; 用戶名 user = root # 密碼 password = root db_name : blog max_idle : 2 max_conn : 10 [array] course = java,go,python
配置文件由一個個的 section 組成,section 下就是key = value或者key : value 這樣的格式配置
如果沒有 section 會放到 DEFAULT 默認section里面
注釋使用 ;開頭或者#開頭
下面我們就來讀取配置
加載、獲取section、獲取單個值、獲取注釋、獲取數(shù)組、重新設置值、刪除值,重新加載文件(會寫一個for循環(huán)10次去重新加載配置,這期間修改配置,觀察值是否改變)
編寫go代碼
package main import ( "errors" "fmt" "github.com/Unknwon/goconfig" "log" "os" "time" ) func main() { currentPath, _ := os.Getwd() confPath := currentPath + "/conf/conf_goconfig.ini" _, err := os.Stat(confPath) if err != nil { panic(errors.New(fmt.Sprintf("file is not found %s", confPath))) } // 加載配置 config, err := goconfig.LoadConfigFile(confPath) if err != nil { log.Fatal("讀取配置文件出錯:", err) } // 獲取 section mysqlConf, _ := config.GetSection("mysql") fmt.Println(mysqlConf) fmt.Println(mysqlConf["host"]) // 獲取單個值 user, _ := config.GetValue("mysql", "user") fmt.Println(user) // 獲取單個值并且指定類型 maxIdle, _ := config.Int("mysql", "max_idle") fmt.Println(maxIdle) // 獲取單個值,發(fā)生錯誤時返回默認值,沒有默認值返回零值 port := config.MustInt("mysql", "port", 3308) fmt.Println(port) // 重新設置值 config.SetValue("mysql", "port", "3307") port = config.MustInt("mysql", "port", 3308) fmt.Println(port) // 刪除值 config.DeleteKey("mysql", "port") port = config.MustInt("mysql", "port", 3308) fmt.Println(port) // 獲取注釋 comments := config.GetKeyComments("mysql", "user") fmt.Println(comments) // 獲取數(shù)組,需要指定分隔符 array := config.MustValueArray("array", "course", ",") fmt.Println(array) // 重新加載配置文件,一般對于web項目,改了配置文件希望能夠即使生效而不需要重啟應用,可以對外提供刷新配置api // 修改password 為 root123值觀察值的變化 for i := 0; i < 10; i++ { time.Sleep(time.Second * 3) _ = config.Reload() password, _ := config.GetValue("mysql", "password") fmt.Println(password) } }
執(zhí)行
map[db_name:blog host:127.0.0.1 max_conn:10 max_idle:2 password:root port:3306 user:root]
127.0.0.1
root
2
3306
3307
3308
; 用戶名
[java go python]
root
root
root
root123
root123
root123
root123
root123
root123
root123
Process finished with the exit code 0
從結(jié)果中可以看出,正確獲取到了配置文件信息,并且可以通過 Reload重新加載配置,達到熱更新效果!
到此這篇關于golang配置文件解析器之goconfig框架的使用詳解的文章就介紹到這了,更多相關go goconfig內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
go開發(fā)alertmanger實現(xiàn)釘釘報警
本文主要介紹了go開發(fā)alertmanger實現(xiàn)釘釘報警,通過自己的url實現(xiàn)alertmanager的釘釘報警,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-07-07Go語言使用ioutil.ReadAll函數(shù)需要注意基本說明
這篇文章主要為大家介紹了Go語言使用ioutil.ReadAll函數(shù)需要注意基本說明,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-07-07