每個(gè)項(xiàng)目中都會(huì)有配置文件管理來(lái)管理,比如數(shù)據(jù)庫(kù)的配置淹遵。
配置文件框架 一般大致思路都是加載配置文件咽安,返回配置操作對(duì)象,該對(duì)象提供獲取配置api
下面我們來(lái)使用goconfig框架來(lái)了解配置框架,它解析的是ini文件,ini文件以簡(jiǎn)單的文字和結(jié)構(gòu)組成烫幕,一般windows系統(tǒng)比較常見(jiàn)俺抽,很多應(yīng)用程序也會(huì)因?yàn)槠浜?jiǎn)單而使用其作為配置文件
官網(wǎng)star目前599
安裝
go get github.com/Unknwon/goconfig
配置示例
在項(xiàng)目下建立一個(gè)文件 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
配置文件由一個(gè)個(gè)的 section 組成,section 下就是key = value或者key : value 這樣的格式配置
如果沒(méi)有 section 會(huì)放到 DEFAULT 默認(rèn)section里面
注釋使用 ;開(kāi)頭或者#開(kāi)頭
下面我們就來(lái)讀取配置
加載较曼、獲取section磷斧、獲取單個(gè)值、獲取注釋诗芜、獲取數(shù)組瞳抓、重新設(shè)置值、刪除值伏恐,重新加載文件(會(huì)寫(xiě)一個(gè)for循環(huán)10次去重新加載配置孩哑,這期間修改配置,觀察值是否改變)
編寫(xiě)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("讀取配置文件出錯(cuò):", err)
}
// 獲取 section
mysqlConf, _ := config.GetSection("mysql")
fmt.Println(mysqlConf)
fmt.Println(mysqlConf["host"])
// 獲取單個(gè)值
user, _ := config.GetValue("mysql", "user")
fmt.Println(user)
// 獲取單個(gè)值并且指定類型
maxIdle, _ := config.Int("mysql", "max_idle")
fmt.Println(maxIdle)
// 獲取單個(gè)值翠桦,發(fā)生錯(cuò)誤時(shí)返回默認(rèn)值横蜒,沒(méi)有默認(rèn)值返回零值
port := config.MustInt("mysql", "port", 3308)
fmt.Println(port)
// 重新設(shè)置值
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)
// 重新加載配置文件销凑,一般對(duì)于web項(xiàng)目丛晌,改了配置文件希望能夠即使生效而不需要重啟應(yīng)用,可以對(duì)外提供刷新配置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é)果中可以看出斗幼,正確獲取到了配置文件信息澎蛛,并且可以通過(guò) Reload重新加載配置,達(dá)到熱更新效果蜕窿!
goconfig的使用就介紹到這里谋逻,大家趕緊用起來(lái)把!
歡迎關(guān)注,學(xué)習(xí)不迷路桐经!