当前位置:网站首页>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
边栏推荐
- Implementation of large file fragment uploading based on webuploader
- 用简单方法实现对象的深克隆封装js
- 关于二分一些模板
- Working method: 3C scheme design method
- P1160 queue arrangement
- Talk about MySQL's locking rule "hard hitting MySQL series 15"
- 机器学习笔记 七:强大的神经网络表述
- tmux -- ssh terminal can be closed without impact the server process
- Gerrit Code Review Setup
- 致远OA漏洞分析、利用与防护合集
猜你喜欢

爬虫初始及项目

SCM future employment development direction, learn SCM must know some entry-level knowledge and industry prospects, read the benefit
![[cloud native] 2.2 kubeadm create cluster](/img/b2/a57b7e44f74357d5aedbb9ddcd95ff.png)
[cloud native] 2.2 kubeadm create cluster

Cookie setting and reading in C #

机器学习笔记 六:逻辑回归中的多分类问题之数字识别

2022 Shanxi secondary vocational group "Cyberspace Security" event module b- web page penetration

Record local project startup error: invalid source distribution: 8

Gerrit Code Review Setup

MinGW下载安装

Someone always asks me: how to play independent station? Three cases, you will understand after reading
随机推荐
Amazon and independent station are not simply two choices
Which is the trend of cross-border policy frequent adjustment of "independent stations & platforms"?
Market consumption survey and investment prospect forecast report of China's graphite industry 2022-2027
爬虫初始及项目
open source hypervisor
给仍在「 选品 」的跨境卖家提个醒!
C#中Cookie设置与读取
大厂晋升学习方法四:Play 学习法
數據的存儲(進階)
中小企业签署ERP合同时,需要留意这几点
移动端 realm数据库使用及解耦,跨线程安全使用 OC realm
Development prospect and investment potential prediction report of China's rare earth permanent magnet industry during the "14th five year plan" period 2022-2027
独立站 “ 去中心化 ” 模式崛起,席卷跨境企业转型浪潮
Opencv function usage details 1~10, including code examples
How wechat applet assigns values to sub components
Leetcode hot1-50
企业如何把ERP项目自动施行?
Talk about MySQL's locking rule "hard hitting MySQL series 15"
想投放Facebook广告却不知从何入手?此文带你深入了解
【毕业季·进击的技术er】一个读研学生的唠唠嗑