105 lines
2.2 KiB
Go
105 lines
2.2 KiB
Go
package config
|
|
|
|
import (
|
|
"os"
|
|
"sync"
|
|
|
|
"gopkg.in/yaml.v2"
|
|
)
|
|
|
|
// Config 结构体定义了应用程序的所有配置项
|
|
type Config struct {
|
|
DB struct {
|
|
Host string `yaml:"host"`
|
|
Port string `yaml:"port"`
|
|
User string `yaml:"user"`
|
|
Password string `yaml:"password"`
|
|
Name string `yaml:"name"`
|
|
} `yaml:"db"`
|
|
|
|
Redis struct {
|
|
Host string `yaml:"host"`
|
|
Port string `yaml:"port"`
|
|
Password string `yaml:"password"`
|
|
DB string `yaml:"db"`
|
|
} `yaml:"redis"`
|
|
|
|
Server struct {
|
|
Port string `yaml:"port"`
|
|
Mode string `yaml:"mode"`
|
|
} `yaml:"server"`
|
|
|
|
Jwt struct {
|
|
Secret string `yaml:"secret"`
|
|
Expire string `yaml:"expire"`
|
|
} `yaml:"jwt"`
|
|
|
|
Mmdb struct {
|
|
Path string `yaml:"path"`
|
|
} `yaml:"mmdb"`
|
|
|
|
Log struct {
|
|
Path string `yaml:"path"`
|
|
} `yaml:"log"`
|
|
}
|
|
|
|
var (
|
|
configInstance *Config
|
|
configOnce sync.Once
|
|
)
|
|
|
|
// LoadConfig 加载并返回应用程序配置(单例模式,只加载一次)
|
|
func LoadConfig() *Config {
|
|
configOnce.Do(func() {
|
|
if cfg := loadConfigFromFile(); cfg != nil {
|
|
configInstance = cfg
|
|
return
|
|
}
|
|
|
|
cfg := &Config{}
|
|
|
|
cfg.DB.Host = getEnv("DB_HOST", "localhost")
|
|
cfg.DB.Port = getEnv("DB_PORT", "3306")
|
|
cfg.DB.User = getEnv("DB_USER", "root")
|
|
cfg.DB.Password = getEnv("DB_PASSWORD", "123456")
|
|
cfg.DB.Name = getEnv("DB_NAME", "quincy")
|
|
|
|
cfg.Redis.Host = getEnv("REDIS_HOST", "localhost")
|
|
cfg.Redis.Port = getEnv("REDIS_PORT", "6379")
|
|
cfg.Redis.Password = getEnv("REDIS_PASSWORD", "")
|
|
cfg.Redis.DB = getEnv("REDIS_DB", "0")
|
|
|
|
cfg.Server.Port = getEnv("SERVER_PORT", "8080")
|
|
cfg.Server.Mode = getEnv("SERVER_MODE", "debug")
|
|
|
|
cfg.Jwt.Secret = getEnv("JWT_SECRET", "your-secret-key")
|
|
cfg.Jwt.Expire = getEnv("JWT_EXPIRE", "24")
|
|
|
|
cfg.Mmdb.Path = getEnv("MMDB_PATH", "./GeoLite2-City.mmdb")
|
|
|
|
cfg.Log.Path = getEnv("LOG_DIR", "./")
|
|
|
|
configInstance = cfg
|
|
})
|
|
|
|
return configInstance
|
|
}
|
|
|
|
func loadConfigFromFile() *Config {
|
|
if data, err := os.ReadFile("/home/app/quincy/default.yaml"); err == nil {
|
|
cfg := &Config{}
|
|
if err := yaml.Unmarshal(data, cfg); err == nil {
|
|
return cfg
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func getEnv(key, defaultValue string) string {
|
|
value := os.Getenv(key)
|
|
if value == "" {
|
|
return defaultValue
|
|
}
|
|
return value
|
|
}
|