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

@@ -0,0 +1,37 @@
package config
type AppConfig struct {
Name string `yaml:"name"`
}
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"`
Socket *struct {
Web *AddressConfig `yaml:"web"`
Raw *AddressConfig `yaml:"raw"`
} `yaml:"socket"`
Http *AddressConfig `yaml:"http"`
}
type AddressConfig struct {
Address string `yaml:"address"`
Port int `yaml:"port"`
}

View File

@@ -0,0 +1,38 @@
package config
import (
"fmt"
"github.com/spf13/viper"
"strings"
)
const (
envConfigPrefix = "XH_G"
)
// LoadConfig 加载并返回应用配置
func LoadConfig[T any](configDir string, configPtr *T) (*T, 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(&configPtr); err != nil {
return nil, fmt.Errorf("解析配置失败: %w", err)
}
return configPtr, nil
}