GoFrame配置文件

GoFrame配置文件

一、配置文件介紹

GF的配置管理由gcfg模塊實現,gcfg模塊是併發安全的,僅提供配置文件讀取功能,不提供數據寫入/修改功能,支持的數據文件格式包括: JSONXMLYAML/YMLTOMLINI,項目中開發者可以靈活地選擇自己熟悉的配置文件格式來進行配置管理。

默認讀取執行文件所在目錄及其下的config目錄,默認讀取的配置文件爲config.toml;toml類型文件也是默認的、推薦的配置文件格式,如果想要自定義文件格式,可以通過SetFileName方法修改默認讀取的配置文件名稱(如:config.json, cfg.yaml, cfg.xml, cfg.ini等等)。

注:TOML大小寫敏感,必須是UTF-8編碼;

二、自動檢測更新

配置管理器使用了緩存機制,當配置文件第一次被讀取後會被緩存到內存中,下一次讀取時將會直接從緩存中獲取,以提高性能。同時,配置管理器提供了對配置文件的自動檢測更新機制,當配置文件在外部被修改後,配置管理器能夠即時地刷新配置文件的緩存內容。

配置管理器的自動檢測更新機制是gf框架特有的一大特色。

三、示例

項目目錄

D:.
│  config_test.go -- 測試文件
│  go.mod
│  go.sum
│  main.go -- web自動更新配置演示
│
├─config
│      config.toml -- 標準配置文件
│
└─configTest -- 定製目錄和配置文件
        config1.toml  
        config2.toml

config.toml

# 模板引擎目錄
viewpath = "/home/www/templates/"
# MySQL數據庫配置
[database]
    [[database.default]]
        host     = "127.0.0.1"
        port     = "3306"
        user     = "root"
        pass     = "123456"
        name     = "test1"
        type     = "mysql"
        role     = "master"
        charset  = "utf8"
        priority = "1"
    [[database.default]]
        host     = "127.0.0.1"
        port     = "3306"
        user     = "root"
        pass     = "123456"
        name     = "test2"
        type     = "mysql"
        role     = "master"
        charset  = "utf8"
        priority = "1"
# Redis數據庫配置
[redis]
    disk  = "127.0.0.1:6379,0"
    cache = "127.0.0.1:6379,1"

config1.toml

study = "hello study"
study1 = "hello study1"

config2.toml

config2 = "111"

main.go

package main

import (
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
)

func main() {
	s := g.Server()
	// 默認路徑
	s.BindHandler("/", func(r *ghttp.Request) {
		r.Response.Writeln("配置",g.Config().GetString("name"))
		r.Response.Writeln("Welcome GoFrame!")
	})

	s.SetPort(80)
	s.Run()

}


config_test.go

package main

import (
	"fmt"
	"github.com/gogf/gf/frame/g"
	"testing"
)

// 基本配置使用
func TestConfig(t *testing.T) {
	// 默認當前路徑或者config路徑,默認文件config.toml
	// /home/www/templates/
	fmt.Println(g.Config().Get("viewpath"))
	fmt.Println(g.Cfg().Get("viewpath"))
	// 127.0.0.1:6379,1
	c := g.Cfg()
	// 分組方式
	fmt.Println(c.Get("redis.cache"))
	// 數組方式:test2
	fmt.Println(c.Get("database.default.1.name"))
}

// 設置路徑
func TestConfig2(t *testing.T) {
	// 設置加載文件,默認name爲default
	// 設置路徑
	g.Cfg().SetPath("configTest")
	// 設置加載文件
	g.Cfg().SetFileName("config1.toml")

	// 打印測試
	fmt.Println(g.Cfg().Get("viewpath"))
	fmt.Println(g.Cfg().Get("study"))
	fmt.Println(g.Cfg().Get("study1"))
	fmt.Println(g.Cfg().Get("config2"))

	// 新的name就是新的實例
	g.Cfg("name").SetPath("configTest")
	g.Cfg("name").SetFileName("config2.toml")
	fmt.Println(g.Cfg("name").Get("viewpath"))
	fmt.Println(g.Cfg("name").Get("study"))
	fmt.Println(g.Cfg("name").Get("study1"))
	fmt.Println(g.Cfg("name").Get("config2"))
}

go.mod

module gf_config

go 1.14

require github.com/gogf/gf v1.15.4

代碼地址

項目視頻

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章