Files

59 lines
1.3 KiB
Go
Raw Permalink Normal View History

2023-09-16 20:14:20 +08:00
package viperx
// Author: yun
// Version: 2023年6月12日18:54:48
import (
"flag"
"fmt"
"log"
"os"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
// 使用viper初始化配置
2023-11-10 00:05:27 +08:00
func InitConfig(path string, data interface{}) error {
2023-09-16 20:14:20 +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 {
2023-11-10 00:05:27 +08:00
return err
2023-09-16 20:14:20 +08:00
}
// 监控配置文件的变化
v.WatchConfig()
// 监听配置的变化
v.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("config file changed:", e.Name)
2023-11-10 00:05:27 +08:00
if err := v.Unmarshal(&data); err != nil {
2023-09-16 20:14:20 +08:00
log.Println(err)
}
})
2023-11-10 00:05:27 +08:00
if err := v.Unmarshal(&data); err != nil {
2023-09-16 20:14:20 +08:00
log.Println(err)
2023-11-10 00:05:27 +08:00
return err
2023-09-16 20:14:20 +08:00
}
2023-11-10 00:05:27 +08:00
return nil
2023-09-16 20:14:20 +08:00
}