Files
sundynix-plant-be/core/viper.go
T
2026-02-06 14:44:06 +08:00

59 lines
1.4 KiB
Go

package core
import (
"flag"
"fmt"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
"os"
"sundynix-go/core/internal"
"sundynix-go/global"
)
func Viper() *viper.Viper {
config := getConfigPath()
v := viper.New()
v.SetConfigFile(config)
v.SetConfigType("yaml")
err := v.ReadInConfig()
if err != nil {
panic(fmt.Errorf("fatal error config file: %w", err))
}
//监听配置文件变化并热加载
v.WatchConfig()
//监听配置文件变化事件
v.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("config file changed:", e.Name)
if err = v.Unmarshal(&global.Config); err != nil {
fmt.Println(err)
}
})
//将读取的配置信息反序列化到全局变量Conf中
if err = v.Unmarshal(&global.Config); err != nil {
panic(fmt.Errorf("fatal error unmarshal config: %w", err))
}
return v
}
// 获取配置文件路径 优先级: 命令行 > 环境变量 > 默认值
func getConfigPath() (config string) {
flag.StringVar(&config, "c", "", "choose config file")
flag.Parse()
// 命令行参数不为空 将值赋值于config
if config != "" {
fmt.Printf("正在使用命令行的 '-c' 参数传递的值, config 的路径为 %s\n", config)
return
}
_, err := os.Stat(config)
if err != nil || os.IsNotExist(err) {
config = internal.ConfigDefaultFile
fmt.Printf("配置文件路径不存在, 使用默认配置文件路径: %s\n", config)
}
return
}