golang 讀取配置檔案vipper
阿新 • • 發佈:2018-11-10
讀取配置檔案的,有toml和vipper兩種好用的方法,toml的方法見:
https://blog.csdn.net/fwhezfwhez/article/details/79272398
最大的特點就是要為配置檔案構建相對應的結構體,有點囧,現在講一個vipper。
config.go
package config
import (
"fmt"
"github.com/fsnotify/fsnotify"
"github.com/fwhezfwhez/errorx"
"os"
"sync"
"github.com/spf13/viper"
)
var config *viper. Viper
var m sync.Mutex
// Init 初始化配置
func init() {
var env string
if env = os.Getenv("ENV"); env=="" {
env = "dev"
}
v := viper.New()
v.SetConfigType("yaml")
v.SetConfigName(env)
v.AddConfigPath("../config/")
v.AddConfigPath("config/")
ReadConfig(v)
v.WatchConfig()
v.OnConfigChange(func(e fsnotify. Event) {
fmt.Println("Config file changed:", e.Name)
})
config = v
}
// GetConfig 獲取配置
func GetConfig() *viper.Viper {
return config
}
func ReadConfig(v *viper.Viper) error{
m.Lock()
defer m.Unlock()
err := v.ReadInConfig()
if err != nil {
return errorx.NewFromString("Error on parsing config file!" )
}
return nil
}
config_test.go
package config
import (
"testing"
)
func TestGetConfig(t *testing.T) {
c := GetConfig()
addr := c.GetString("addr")
fmt.Println(addr)
host := c.GetString("db.host")
fmt.Println(host)
time.Sleep(20 * time.Second)
// 這時候去修改 dev.yaml
}
在二者的同級目錄下:
dev.yaml
addr: :8090
debugPort: :8091
db:
host: localhost
port: 5432
執行config_test 檔案:
=== RUN TestGetConfig
:8090
localhost
Config file changed: G:\go_workspace\GOPATH\src\cdd-platform-srv\config\dev.yaml