Files
elevator-server/core/viper/viper.go
2024-12-23 18:43:29 +08:00

55 lines
1.1 KiB
Go

package viper
import (
"DT/config"
"DT/global"
"flag"
"fmt"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
"os"
)
func InitViper(path ...string) {
var confPath string
if len(path) == 0 {
flag.StringVar(&confPath, "c", "", "choose config file.")
flag.Parse()
if confPath == "" {
if AppEnv := os.Getenv(config.AppEnv); AppEnv == "" {
confPath = config.EnvConfig
} else {
confPath = AppEnv
}
} else {
}
} else {
confPath = path[0]
}
v := viper.New()
v.SetConfigFile(confPath)
v.SetConfigType("yaml")
err := v.ReadInConfig()
if err != nil {
fmt.Printf("[-]读取配置文件错误: %s \n", err)
os.Exit(0)
}
v.WatchConfig()
v.OnConfigChange(func(e fsnotify.Event) {
if err = v.Unmarshal(&global.AppConf); err != nil {
fmt.Printf("[-]重新解析配置文件失败: %s \n", err)
os.Exit(0)
}
fmt.Println("[+]重新加载配置文件完成")
})
if err = v.Unmarshal(&global.AppConf); err != nil {
fmt.Printf("[-]解析配置文件失败: %s \n", err)
os.Exit(0)
}
fmt.Println("[+]加载配置文件完成")
//dump.P(global.AppConf)
}