go配置文件讀取

一個強大簡單好用的配置解決方案,Vipergit

Viper具備如下特性:github

  • 設置默認值
  • 能夠讀取以下格式的配置文件:JSON、TOML、YAML、HCL
  • 監控配置文件改動,並熱加載配置文件
  • 從環境變量讀取配置
  • 從遠程配置中心讀取配置(etcd/consul),並監控變更
  • 從命令行 flag 讀取配置
  • 從緩存中讀取配置
  • 支持直接設置配置項的值

Viper的讀取順序:緩存

  • viper.Set() 所設置的值
  • 命令行 flag
  • 環境變量
  • 配置文件
  • 配置中心:etcd/consul
  • 默認值

Viper在初始化以後,只須要調用viper.GetString()viper.GetInt()viper.GetBool() 等函數便可獲得配置文件中對應的參數。微信

Viper 也能夠很是方便地讀取多個層級的配置,好比這樣一個 YAML 格式的配置:函數

common:
 db:
 name: db
 addr: 127.0.0.1:3306
 username: root
 password: root
複製代碼

若是要讀取name,只須要執行viper.GetString("common.db.name")就能夠ui

下面來一個簡單的例子介紹Viper: config/config.gospa

package config

import (
	"strings"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)

type Config struct {
	Name string
}

func Init(cfg string) error {
	c := Config{
		Name: cfg,
	}
    // 初始化配置文件
	if err := c.initConfig(); err != nil {
		return err
	}
	
	c.watchConfig()

	return nil
}

func (c *Config) initConfig() error {
	if c.Name != "" {
	   // 若是指定了配置文件,則解析指定的配置文件
		viper.SetConfigFile(c.Name)
	} else {
	   // 若是沒有指定配置文件,則解析默認的配置文件
		viper.AddConfigPath("conf")
		viper.SetConfigName("config")
	}
   // 設置配置文件格式爲YAML
	viper.SetConfigType("yaml")
	// viper解析配置文件
	if err := viper.ReadInConfig(); err != nil {
		return err
	}

	return nil
}

// 監聽配置文件是否改變,用於熱更新
func (c *Config) watchConfig() {
	viper.WatchConfig()
	viper.OnConfigChange(func(e fsnotify.Event) {
		fmt.Printf("Config file changed: %s\n", e.Name)
	})
}

複製代碼

conf/config.yaml命令行

name: demo
common:
 db:
 name: db
 addr: 127.0.0.1:3306
 username: root
 password: root
複製代碼

main.gocode

package main

import (
	"test/config"
  "fmt"
	"github.com/spf13/viper"
)

func main() {

	if err := config.Init(""); err != nil {
		panic(err)
	}

	name := viper.GetString("name")

	fmt.Println("Viper get name:",name)
}

複製代碼

執行go run main.gocdn

輸出Viper get name: demo

微信搜索「goentry-xyz」,關注公衆號「燈下獨碼」

相關文章
相關標籤/搜索