This commit is contained in:
2025-06-29 10:39:00 +08:00
parent 605197345b
commit b45eb83fe4
15 changed files with 597 additions and 3 deletions

View File

@@ -0,0 +1,19 @@
app:
name: "gateway-dev"
log:
debug: true
level: "debug"
max_size: 100
max_backups: 3
max_age: 7
db:
etcd:
address: [ "10.0.40.9:2379" ]
serve:
grpc:
address: "127.0.0.1"
port: 8504
ttl: 20

View File

@@ -0,0 +1,43 @@
package config
type Config struct {
App *AppConfig `yaml:"app"`
Log *LogConfig `yaml:"log"`
DB *DBConfig `yaml:"db"`
Serve *ServeConfig `yaml:"serve"`
}
type AppConfig struct {
Name string `yaml:"name"`
}
type LogConfig struct {
Debug bool `yaml:"debug"`
MaxSize int `yaml:"max_size"`
MaxBackups int `yaml:"max_backups"`
MaxAge int `yaml:"max_age"`
Level string `yaml:"level"`
}
type DBConfig struct {
Etcd *struct {
Address []string `yaml:"address"`
} `yaml:"etcd"`
}
type ServeConfig struct {
Grpc *struct {
AddressConfig
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,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
}