u
This commit is contained in:
1 parent
26ff2381b7
commit
00a1cce5ac
22 files changed
+335
-215
No files matched your search
@@ -3,9 +3,10 @@ package config
|
||||
import (
|
||||
"allapp/db"
|
||||
"allapp/utils/redisx"
|
||||
"bytes"
|
||||
_ "embed"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -83,50 +84,45 @@ func defaultConfig() *Config {
|
||||
}
|
||||
}
|
||||
|
||||
//go:embed resources/application.yaml
|
||||
var defaultYaml []byte
|
||||
|
||||
//go:embed resources/application-dev.yaml
|
||||
var devYaml []byte
|
||||
|
||||
//go:embed resources/application-build.yaml
|
||||
var buildYaml []byte
|
||||
|
||||
func readConfigFile() error {
|
||||
// 配置文件的目录
|
||||
prefix := "resources"
|
||||
env := GetEnv() // 获取当前环境
|
||||
conf = defaultConfig()
|
||||
env := GetEnv()
|
||||
|
||||
// 设置默认值
|
||||
conf = defaultConfig() // 先给默认结构体
|
||||
|
||||
// 默认配置文件
|
||||
confFileRelPath := filepath.Join(prefix, "application.yaml")
|
||||
|
||||
// 创建 viper 实例
|
||||
v := viper.New()
|
||||
|
||||
// 首先加载默认的 application.yaml
|
||||
v.SetConfigFile(confFileRelPath)
|
||||
v.SetConfigType("yaml")
|
||||
|
||||
// 读取默认配置文件
|
||||
if err := v.ReadInConfig(); err != nil {
|
||||
panic(err)
|
||||
// 读取默认配置
|
||||
if err := v.ReadConfig(bytes.NewReader(defaultYaml)); err != nil {
|
||||
return fmt.Errorf("read default config failed: %w", err)
|
||||
}
|
||||
|
||||
// 根据环境加载不同的配置文件
|
||||
// 根据环境合并
|
||||
switch env {
|
||||
case "dev":
|
||||
v.SetConfigFile(filepath.Join(prefix, "application-dev.yaml"))
|
||||
case "build":
|
||||
v.SetConfigFile(filepath.Join(prefix, "application-build.yaml"))
|
||||
if err := v.MergeConfig(bytes.NewReader(buildYaml)); err != nil {
|
||||
return fmt.Errorf("merge build config failed: %w", err)
|
||||
}
|
||||
default: // dev 或其他值都使用 dev
|
||||
if err := v.MergeConfig(bytes.NewReader(devYaml)); err != nil {
|
||||
return fmt.Errorf("merge dev config failed: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 如果需要,合并环境特定的配置文件
|
||||
if err := v.MergeInConfig(); err != nil {
|
||||
return fmt.Errorf("merge env config failed: %w", err)
|
||||
}
|
||||
|
||||
if err := v.Unmarshal(conf); err != nil {
|
||||
if err := v.Unmarshal(&conf); err != nil {
|
||||
return fmt.Errorf("unmarshal config failed: %w", err)
|
||||
}
|
||||
|
||||
fmt.Println("✅️ 加载配置成功")
|
||||
// 设置环境变量
|
||||
conf.Env = env
|
||||
|
||||
fmt.Println("✅ 加载配置成功, 环境:", env)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user