当前位置:网站首页>Introduction to golang Viper Library

Introduction to golang Viper Library

2022-06-22 05:43:00 weixin_ forty-six million two hundred and seventy-two thousand

install Viper

go get github.com/spf13/viper

Viper Read configuration file

viper.SetConfigFile("./config.yaml") //  Specify the profile path 
viper.SetConfigName("config") //  Profile name ( No extension )
viper.SetConfigType("yaml") //  If there is no extension in the name of the configuration file , You need to configure this 
viper.AddConfigPath("/etc/appname/")   //  Find the path where the configuration file is located 
viper.AddConfigPath("$HOME/.appname")  //  Multiple calls to add multiple search paths 
viper.AddConfigPath(".")               //  You can also find the configuration in the working directory 
err := viper.ReadInConfig() //  Find and read the configuration file 
if err != nil {
     //  Handle errors reading configuration files 
	panic(fmt.Errorf("Fatal error config file: %s \n", err))
}

There are many methods above , But just for more freedom of use , We can directly specify the access configuration file path

viper.SetConfigFile("./config.yaml") //  Specify the profile path 

You can also find the configuration file in multiple ways ( Multiple files with different file formats may be used ).

viper.SetConfigName("config") //  Profile name ( No extension )
viper.SetConfigType("yaml") //  If there is no extension in the name of the configuration file , You need to configure this 
viper.AddConfigPath("./conf")   //  Find the path where the configuration file is located 

In the following case , If there is... Under the same folder ./conf/config.yaml and ./conf/config.json,viper Preference will be given json Format of the configuration file

viper.SetConfigName("config") //  Profile name ( No extension )
viper.AddConfigPath("./conf")   //  Find the path where the configuration file is located 

Viper Thermal loading

If you change the configuration file while running , Then we need to recompile the program . fortunately ,Viper We have added the function of hot loading .

viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
    
  //  The callback function that will be called after the configuration file is changed 
	fmt.Println("Config file changed:", e.Name)
})

Viper Use cases

yaml Format of the configuration file config.yaml

mysql:
  host: "127.0.0.1"
  port: 3306
  user: "root"
  password: "123456jkld"
  database: "user"

json Format of the configuration file config.json

{
    
  "mysql": {
    
    "host": "127.0.0.1",
    "port": 3306,
    "user": "root",
    "password": "123456jkld",
    "database": "user"
  }
}

main.go

package main

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"github.com/spf13/viper"
)

var DB *gorm.DB

func configInit() {
    
	viper.SetConfigFile("./conf/config.yaml") //  Specify the profile path 
	//viper.SetConfigFile("./conf/config.json")

	err := viper.ReadInConfig() //  Find and read the configuration file 
	if err != nil {
                 //  Handle errors reading configuration files 
		panic(fmt.Errorf("Fatal error config file: %s \n", err))
	}
	//  Monitoring profile changes 
	viper.WatchConfig()
	viper.OnConfigChange(func(e fsnotify.Event) {
    
		//  The callback function that will be called after the configuration file is changed 
		fmt.Println("Config file changed:", e.Name)
	})
}

func mysqlInit() {
    
	// viper  Get configuration information 
	user := viper.GetString("mysql.user")
	password := viper.GetString("mysql.password")
	host := viper.GetString("mysql.host")
	port := viper.GetInt("mysql.port")
	database := viper.GetString("mysql.database")

	//  Connect to database 
	dsn := fmt.Sprintf("%s:%[email protected](%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", user, password, host, port, database)
	db, err := gorm.Open("mysql", dsn)
	if err != nil {
    
		panic(err)
	}
	//  Assign to global variable 
	DB = db
}

func main() {
    

	//  Read configuration information 
	configInit()

	//  Database connection initialization 
	mysqlInit()
    
    //  If there is an error in any link, an error will be reported 
    fmt.Println("Success!")
}

Use structure variables to save configuration information

Viper It also supports saving configuration information to a custom structure , The main use of Unmarshal(rawVal interface{}) : error Method

config.yaml

introduction:
  name: "test_project"
  version: "0.0.1"


mysql:
  host: "127.0.0.1"
  port: 3306
  user: "root"
  password: "123456jkld"
  database: "user"

main.go

package main

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

type Config struct {
    
	*IntroductionConfig `mapstructure:"introduction"`
	*MySQLConfig        `mapstructure:"mysql"`
}

type IntroductionConfig struct {
    
	Name    string `mapstructure:"name"`
	Version string `mapstructure:"version"`
}

type MySQLConfig struct {
    
	Host     string `mapstructure:"host"`
	User     string `mapstructure:"user"`
	Password string `mapstructure:"password"`
	DB       string `mapstructure:"database"`
	Port     int    `mapstructure:"port"`
}

var config = new(Config)

func main() {
    
	viper.SetConfigFile("./conf/config.yaml") //  Specify the profile path 
	err := viper.ReadInConfig()               //  Read configuration information 
	if err != nil {
                               //  Failed to read configuration information 
		panic(fmt.Errorf("Fatal error config file: %s \n", err))
	}

	//  Save the read configuration information to the global variable  config
	if err := viper.Unmarshal(config); err != nil {
    
		panic(err)
	}

	fmt.Printf("%#v\n", *(config.MySQLConfig))        // main.MySQLConfig{Host:"127.0.0.1", User:"root", Password:"123456jkld", DB:"user", Port:3306}
	fmt.Printf("%#v\n", *(config.IntroductionConfig)) // main.IntroductionConfig{Name:"test_project", Version:"0.0.1"}

}

remember , When parsing configuration information into a structure, you must use mapstructure Field .

Reference resources

原网站

版权声明
本文为[weixin_ forty-six million two hundred and seventy-two thousand ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220529488562.html