golang 读取配置文件vipper

读取配置文件的,有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

猜你喜欢

转载自blog.csdn.net/fwhezfwhez/article/details/83146356