Files
viperx/viperx.go
T

68 lines
1.5 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-03-13 14:27:42 +08:00
func InitConfig(path string, data interface{}) {
2024-03-13 14:10:15 +08:00
2024-03-13 14:16:45 +08:00
// 判断是否指针
if reflect.ValueOf(data).Kind() != reflect.Ptr {
2024-03-13 14:27:42 +08:00
panic("data must be a pointer")
// return errors.New("data must be a pointer")
2024-03-13 14:16:45 +08:00
}
2024-03-13 14:10:15 +08:00
if len(path) == 0 {
flag.StringVar(&path, "c", "", "choose config file.")
flag.Parse()
if path == "" { // 优先级: 命令行 > 环境变量 > 默认值
if configEnv := os.Getenv("config"); configEnv == "" {
path = "config.yaml"
log.Printf("您正在使用config的默认值,config的路径为%v\n", path)
} else {
path = configEnv
log.Printf("您正在使用GVA_CONFIG环境变量,config的路径为%v\n", path)
}
} else {
log.Printf("您正在使用命令行的-c参数传递的值,config的路径为%v\n", path)
}
}
v := viper.New()
v.SetConfigFile(path)
err := v.ReadInConfig()
if err != nil {
2024-03-13 14:27:42 +08:00
panic(fmt.Errorf("Fatal error config file: %s \n", err))
// return err
2024-03-13 14:10:15 +08:00
}
// 监控配置文件的变化
v.WatchConfig()
// 监听配置的变化
v.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("config file changed:", e.Name)
if err := v.Unmarshal(&data); err != nil {
log.Println(err)
}
})
if err := v.Unmarshal(&data); err != nil {
log.Println(err)
2024-03-13 14:27:42 +08:00
panic(fmt.Errorf("Fatal error config file: %s \n", err))
// return err
2024-03-13 14:10:15 +08:00
}
2024-03-13 14:27:42 +08:00
// return nil
2024-03-13 14:10:15 +08:00
}