首页 > 其他分享 >Viper读取配置文件

Viper读取配置文件

时间:2022-12-17 20:22:47浏览次数:43  
标签:读取 配置文件 err int viper mapstructure string Viper

写项目时总会需要配置文件,Go语言中可以使用viper来读取配置文件。

go get "github.com/spf13/viper"

例子, 现在有一个conf.yaml

name: "helloViper"
port: 8080
mode: "dev"
version: "v1"
machineID: 1  # 用于生成UUID
startTime: "2022-12-17"

logger:
	level: "debug"
	filename: "helloViper.log"
	max_size: 200
	max_age: 30
	max_backups: 7

mysql:
	host: "localhost"
	port: 3306
	user: "root"
	password: "helloViper"
	dbname: "helloViper"

redis:
	host: "localhost"
	port: "6379"
	db: 0
	password: ""

用viper读取上面的配置信息,conf.go

package conf

import (
	"fmt"
	"github.com/spf13/viper"
	"github.com/fsnotify/fsnotify"
)
// 创建结构体变量用来存放配置信息, 注意内存对齐,相同类型变量写在一起
// 创建一个全局的变量,方便使用配置信息
var Conf = new(AppConf)

type AppConf struct {
	Name string `mapstructure:"name"`
	Mode string `mapstructure:"mode"`
	Version string `mapstructure:"version"`
	StartTime string `mapstructure:"startTime"`
	MachineID int `mapstructure:"machineID"`
	Port int `mapstructure:"port"`
	*LoggerConf
	*MysqlConf
	*RedisConf
}

type LoggerConf struct {
	Level string `mapstructure:"level"`
	Filename string `mapstructure:"filename"`
	MaxAge int `mapstructure:"max_age"`
	MaxSize int `mapstructure:"max_size"`
	MaxBackups int `mapstructure:"max_backups"`
}

type MysqlConf struct {
	Host string `mapstructure:"host"`
	User string `mapstructure:"user"`
	Password string `mapstructure:"password"`
	DBname string `mapstructure:"dbname"`
	Port int `mapstructure:"port"`
}

type RedisConf struct {
	Host string `mapstructure:"host"`
	Password string `mapstructure:"password"`
	DB int `mapstructure:"db"`
	Port int `mapstructure:"port"`
}

func Init() (err error){
	// 设置配置文件信息
	viper.SetConfigName("conf")
		// 配合远程配置中心使用可以配置多个类型
	viper.SetConfigType("yaml")
	viper.AddConfigPath(".")
	// 读取配置文件
  if	err := viper.ReadInConfig(); err != nil {
		fmt.Printf("viper.ReadInConfig() failed, err:%v\\n",err)
		return
	}
	// 通过反射,赋值给结构体变量
	if err := viper.Unmarshal(Conf); err != nil {
		fmt.Printf("viper.Unmarshal() failed, err:%v\\n",err)
		return
	}
	//监视配置文件,实现热加载
	viper.WatchConfig()
	viper.OnConfigChange(func (fs fsnotify.Event) {
		fmt.Println("配置文件修改了.....")
		if err := viper.Unmarshal(Conf); err != nil {
			fmt.Printf("viper.Unmarshal(Conf) failed, err:%v\\n",err)
			return
		}
	})
	return
}

主程序使用

package main

import (
		"helloViper/conf"
		"helloViper/dao/mysql"
)

func main() {
	// 加载配置文件
	if err := conf.Init(); err != nil {
		fmt.Printf("conf.Init() failed, err:%v\\n",err)
		return
	}
	// 加载mysql配置去初始化
	if err := mysql.Init(conf.Conf.MysqlConf); err != nil {
		fmt.Printf("mysql.Init() failed, err:%v\\n",err)
		return 
	}
}

标签:读取,配置文件,err,int,viper,mapstructure,string,Viper
From: https://www.cnblogs.com/kanx1blog/p/16989472.html

相关文章