修改参数获取

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