feat: load backend config from yaml

This commit is contained in:
2026-07-18 21:01:34 +08:00
parent 250b71951e
commit 62bd3d0455
5 changed files with 183 additions and 32 deletions

View File

@@ -1,32 +1,44 @@
package config
import "os"
import (
"os"
"path/filepath"
"strings"
"gopkg.in/yaml.v3"
)
type Config struct {
Env string
Port string
DatabaseURL string
StorageDir string
AuthSecret string
SystemAIKey string
AIKeyEncryptionSecret string
Env string `yaml:"env"`
Port string `yaml:"port"`
DatabaseURL string `yaml:"database_url"`
StorageDir string `yaml:"storage_dir"`
AuthSecret string `yaml:"auth_secret"`
SystemAIKey string `yaml:"system_ai_key"`
AIKeyEncryptionSecret string `yaml:"ai_key_encryption_secret"`
}
func Load() Config {
return Config{
Env: getenv("APP_ENV", "development"),
Port: getenv("PORT", "8080"),
DatabaseURL: getenv("DATABASE_URL", "postgres://agent:agent@localhost:5432/agent?sslmode=disable"),
StorageDir: getenv("STORAGE_DIR", "./data/files"),
AuthSecret: getenv("AUTH_SECRET", "development-auth-secret-change-me"),
SystemAIKey: os.Getenv("SYSTEM_AI_KEY"),
AIKeyEncryptionSecret: getenv("AI_KEY_ENCRYPTION_SECRET", "development-ai-key-secret-change-me"),
cfg, err := LoadFromDir("etc")
if err != nil {
panic(err)
}
return cfg
}
func getenv(key string, fallback string) string {
if value := os.Getenv(key); value != "" {
return value
func LoadFromDir(configDir string) (Config, error) {
mode := strings.TrimSpace(os.Getenv("SENLIN_APP_MODE"))
if mode == "" {
mode = "dev"
}
return fallback
path := filepath.Join(configDir, "agent."+strings.ToLower(mode)+".yaml")
data, err := os.ReadFile(path)
if err != nil {
return Config{}, err
}
var cfg Config
if err := yaml.Unmarshal(data, &cfg); err != nil {
return Config{}, err
}
return cfg, nil
}