Files

75 lines
1.8 KiB
Go
Raw Permalink Normal View History

2024-05-26 00:04:09 +08:00
package viperx
// Author: yun
// Version: 2023年6月12日18:54:48
import (
"flag"
"fmt"
"log"
"os"
"path/filepath"
"reflect"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
// 使用viper初始化配置
// @param configPath 配置文件路径
// @param configData 配置数据结构体指针
func InitConfig(configData interface{}, defaultPath string) {
// 判断是否指针
if reflect.ValueOf(configData).Kind() != reflect.Ptr {
panic("接收数据需要是指针类型")
}
// 优先级: 命令行 > 环境变量 > 默认值
filePath := ""
flag.StringVar(&filePath, "c", "", "choose config file.")
flag.Parse()
if filePath == "" {
if configEnv := os.Getenv("config"); configEnv == "" {
filePath = defaultPath
log.Printf("您正在使用config的默认值,config的路径为%v\n", filePath)
} else {
filePath = configEnv
log.Printf("您正在使用GVA_CONFIG环境变量,config的路径为%v\n", filePath)
}
} else {
log.Printf("您正在使用命令行的-c参数传递的值,config的路径为%v\n", filePath)
}
absPath, _ := filepath.Abs(filePath)
log.Println("配置文件路径:", absPath)
v := viper.New()
v.SetConfigFile(filePath)
err := v.ReadInConfig()
if err != nil {
panic(fmt.Sprintf("Fatal error config file: %s \n", err))
}
// 监控配置文件的变化
v.WatchConfig()
// 监听配置的变化
v.OnConfigChange(func(e fsnotify.Event) {
log.Println("config file changed:", e.Name)
if err := v.Unmarshal(&configData); err != nil {
log.Println(err)
}
})
// 将配置文件的内容映射到configData中
if err := v.Unmarshal(&configData); err != nil {
log.Println(err)
panic(fmt.Sprintf("Fatal error config file: %s \n", err))
}
}