加入网络层
This commit is contained in:
45
Server/Gateway/config/loader.go
Normal file
45
Server/Gateway/config/loader.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/spf13/viper"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultConfigName = "config.dev"
|
||||
envConfigPrefix = "XH_G"
|
||||
)
|
||||
|
||||
var cfg *Config
|
||||
|
||||
// LoadConfig 加载并返回应用配置
|
||||
func LoadConfig(configDir string) (*Config, error) {
|
||||
v := viper.New()
|
||||
|
||||
v.SetEnvPrefix(envConfigPrefix)
|
||||
v.AutomaticEnv()
|
||||
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
|
||||
|
||||
env := v.GetString("env")
|
||||
if env == "" {
|
||||
env = "dev"
|
||||
}
|
||||
|
||||
v.SetConfigName(fmt.Sprintf("config.%s", strings.ToLower(env)))
|
||||
v.AddConfigPath(configDir)
|
||||
v.SetConfigType("yaml")
|
||||
|
||||
if err := v.ReadInConfig(); err != nil {
|
||||
return nil, fmt.Errorf("读取配置失败: %w", err)
|
||||
}
|
||||
|
||||
if err := v.Unmarshal(&cfg); err != nil {
|
||||
return nil, fmt.Errorf("解析配置失败: %w", err)
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func Get() *Config {
|
||||
return cfg
|
||||
}
|
||||
Reference in New Issue
Block a user