feat config

This commit is contained in:
2025-12-11 11:12:36 +08:00
parent d6f770fbb3
commit 71d4e593c7
19 changed files with 229 additions and 326 deletions

View File

@@ -1,34 +1,25 @@
package config
import "common/config"
const path = "./config"
type Config struct {
App *AppConfig `yaml:"app"`
Log *LogConfig `yaml:"log"`
DB *DBConfig `yaml:"db"`
Serve *ServeConfig `yaml:"serve"`
App *config.AppConfig `yaml:"app"`
Log *config.LogConfig `yaml:"log"`
DB *config.DBConfig `yaml:"db"`
Serve *config.ServeConfig `yaml:"serve"`
}
type AppConfig struct {
Name string `yaml:"name"`
var cfg *Config
// LoadConfig 加载应用配置
func LoadConfig() error {
c, err := config.LoadConfig(path, cfg)
cfg = c
return err
}
type LogConfig struct {
Debug bool `yaml:"debug"`
MaxSize int `yaml:"maxSize"`
MaxBackups int `yaml:"maxBackups"`
MaxAge int `yaml:"maxAge"`
Level string `yaml:"level"`
}
type DBConfig struct {
Etcd *struct {
Address []string `yaml:"address"`
} `yaml:"etcd"`
}
type ServeConfig struct {
Grpc *struct {
Address string `yaml:"address"`
Port int `yaml:"port"`
TTL int64 `yaml:"ttl"`
} `yaml:"grpc"`
func Get() *Config {
return cfg
}

View File

@@ -1,45 +0,0 @@
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
}