feat: 读取不同环境配置文件

This commit is contained in:
Blizzard
2025-04-24 21:54:49 +08:00
parent 991f37b13a
commit 1de88e2dac
13 changed files with 155 additions and 32 deletions
+8
View File
@@ -0,0 +1,8 @@
package internal
const (
ConfigDefaultFile = "config-dev.yaml"
ConfigProdFile = "config-prod.yaml"
ConfigDebugFile = "config-debug.yaml"
ConfigReleaseFile = "config-release.yaml"
)
+46 -18
View File
@@ -1,32 +1,60 @@
package core
import (
"flag"
"fmt"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
"sundynix-go/config"
"os"
"sundynix-go/core/internal"
"sundynix-go/global"
)
func Viper() (cfg *config.Config) {
viper.SetConfigFile("config.yaml")
viper.SetConfigType("yaml")
viper.AddConfigPath("../")
func Viper() *viper.Viper {
config := getConfigPath()
fmt.Println("配置文件路径:", config)
v := viper.New()
v.AddConfigPath("../../config-dev.yaml")
v.SetConfigFile(config)
v.SetConfigType("yaml")
if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
// Config file not found; ignore error if desired
fmt.Println("Config file not found")
} else {
// Config file was found but another error was produced
fmt.Println("Read config file error ")
}
err := v.ReadInConfig()
if err != nil {
panic(fmt.Errorf("fatal error config file: %w", err))
}
//将所有值或特定值解组到结构、映射中
//反序列化所有配置项
if err := viper.Unmarshal(&cfg); err != nil {
fmt.Printf("unmarshal error %s", 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
}