Files
viperx/viperx.go
T

71 lines
1.7 KiB
Go
Raw Normal View History

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