u
This commit is contained in:
1 parent
835958886e
commit
d04d22723b
155 files changed
+543
-9793
No files matched your search
@@ -0,0 +1,71 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var (
|
||||
conf *Config
|
||||
)
|
||||
|
||||
func InitConf() {
|
||||
// 配置文件的目录
|
||||
prefix := "resources"
|
||||
env := GetEnv() // 获取当前环境
|
||||
|
||||
// 默认配置文件
|
||||
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)
|
||||
}
|
||||
|
||||
// 根据环境加载不同的配置文件
|
||||
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.MergeInConfig(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// 将配置文件反序列化到 Config 结构体
|
||||
conf = new(Config)
|
||||
if err := v.Unmarshal(conf); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
fmt.Println("✅️ 加载配置成功")
|
||||
// 设置环境变量
|
||||
conf.Env = env
|
||||
}
|
||||
|
||||
// GetEnv 获取 GO_ENV 环境变量,默认返回 "dev"
|
||||
func GetEnv() string {
|
||||
e := os.Getenv("GO_ENV")
|
||||
if len(e) == 0 {
|
||||
// 如果没有设置 GO_ENV,使用默认的 "dev" 配置
|
||||
return "dev"
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
func GetConf() *Config {
|
||||
return conf
|
||||
}
|
||||
Reference in new issue
Block a user