feat: update configuration loading to use viper and add environment variable overrides
This commit is contained in:
@@ -3,9 +3,9 @@ package config
|
||||
import (
|
||||
"agent-desk/internal/pkg/enums"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
@@ -199,13 +199,19 @@ type WxWorkConfig struct {
|
||||
}
|
||||
|
||||
func Load(path string) (*Config, error) {
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
v := viper.New()
|
||||
v.SetConfigFile(path)
|
||||
v.SetConfigType("yaml")
|
||||
v.SetEnvPrefix("AGENT_DESK")
|
||||
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
|
||||
v.AutomaticEnv()
|
||||
|
||||
if err := v.ReadInConfig(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cfg := &Config{}
|
||||
if err := yaml.Unmarshal(b, cfg); err != nil {
|
||||
if err := v.Unmarshal(cfg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cfg, nil
|
||||
|
||||
@@ -35,3 +35,48 @@ func TestLoadReadsCORSAllowedOrigins(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadOverridesValuesFromEnvironment(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.yaml")
|
||||
content := []byte(`server:
|
||||
port: 8083
|
||||
db:
|
||||
type: sqlite
|
||||
dsn: file:./data/app.db?_busy_timeout=5000
|
||||
storage:
|
||||
local:
|
||||
baseUrl: /storage
|
||||
mcp:
|
||||
servers:
|
||||
system:
|
||||
endpoint: http://127.0.0.1:8083/api/mcp
|
||||
`)
|
||||
if err := os.WriteFile(path, content, 0600); err != nil {
|
||||
t.Fatalf("WriteFile() error = %v", err)
|
||||
}
|
||||
t.Setenv("AGENT_DESK_SERVER_PORT", "8090")
|
||||
t.Setenv("AGENT_DESK_DB_DSN", "mysql-dsn")
|
||||
t.Setenv("AGENT_DESK_STORAGE_LOCAL_BASEURL", "/files")
|
||||
t.Setenv("AGENT_DESK_MCP_SERVERS_SYSTEM_ENDPOINT", "http://127.0.0.1:8090/api/mcp")
|
||||
|
||||
cfg, err := Load(path)
|
||||
if err != nil {
|
||||
t.Fatalf("Load() error = %v", err)
|
||||
}
|
||||
|
||||
if cfg.Server.Port != 8090 {
|
||||
t.Fatalf("Server.Port=%d want 8090", cfg.Server.Port)
|
||||
}
|
||||
if cfg.DB.Type != "sqlite" {
|
||||
t.Fatalf("DB.Type=%q want sqlite", cfg.DB.Type)
|
||||
}
|
||||
if cfg.DB.DSN != "mysql-dsn" {
|
||||
t.Fatalf("DB.DSN=%q want mysql-dsn", cfg.DB.DSN)
|
||||
}
|
||||
if cfg.Storage.Local.BaseURL != "/files" {
|
||||
t.Fatalf("Storage.Local.BaseURL=%q want /files", cfg.Storage.Local.BaseURL)
|
||||
}
|
||||
if cfg.MCP.Servers["system"].Endpoint != "http://127.0.0.1:8090/api/mcp" {
|
||||
t.Fatalf("MCP system endpoint=%q", cfg.MCP.Servers["system"].Endpoint)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user