mirror of
https://github.com/sky22333/hubproxy.git
synced 2026-08-06 04:05:17 +08:00
更新构建配置并补充测试
This commit is contained in:
@@ -197,16 +197,23 @@ func setConfig(cfg *AppConfig) {
|
||||
configCacheMutex.Unlock()
|
||||
}
|
||||
|
||||
// LoadConfig 加载配置文件
|
||||
func configFilePath() string {
|
||||
if path := strings.TrimSpace(os.Getenv("CONFIG_PATH")); path != "" {
|
||||
return path
|
||||
}
|
||||
return "config.toml"
|
||||
}
|
||||
|
||||
func LoadConfig() error {
|
||||
cfg := DefaultConfig()
|
||||
path := configFilePath()
|
||||
|
||||
if data, err := os.ReadFile("config.toml"); err == nil {
|
||||
if data, err := os.ReadFile(path); err == nil {
|
||||
if err := toml.Unmarshal(data, cfg); err != nil {
|
||||
return fmt.Errorf("解析配置文件失败: %v", err)
|
||||
return fmt.Errorf("解析配置文件 %s 失败: %v", path, err)
|
||||
}
|
||||
} else {
|
||||
fmt.Println("未找到config.toml,使用默认配置")
|
||||
fmt.Printf("未找到配置文件 %s,使用默认配置\n", path)
|
||||
}
|
||||
|
||||
overrideFromEnv(cfg)
|
||||
@@ -259,6 +266,10 @@ func overrideFromEnv(cfg *AppConfig) {
|
||||
cfg.Security.BlackList = append(cfg.Security.BlackList, strings.Split(val, ",")...)
|
||||
}
|
||||
|
||||
if val, ok := os.LookupEnv("ACCESS_PROXY"); ok {
|
||||
cfg.Access.Proxy = strings.TrimSpace(val)
|
||||
}
|
||||
|
||||
if val := os.Getenv("MAX_IMAGES"); val != "" {
|
||||
if maxImages, err := strconv.Atoi(val); err == nil && maxImages > 0 {
|
||||
cfg.Download.MaxImages = maxImages
|
||||
|
||||
41
src/config/config_test.go
Normal file
41
src/config/config_test.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLoadConfigUsesConfigPathAndEnvOverrides(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "custom.toml")
|
||||
data := []byte(`
|
||||
[server]
|
||||
host = "127.0.0.1"
|
||||
port = 5999
|
||||
|
||||
[access]
|
||||
proxy = "socks5://127.0.0.1:1080"
|
||||
`)
|
||||
if err := os.WriteFile(path, data, 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
t.Setenv("CONFIG_PATH", path)
|
||||
t.Setenv("SERVER_PORT", "6001")
|
||||
t.Setenv("ACCESS_PROXY", "")
|
||||
|
||||
if err := LoadConfig(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg := GetConfig()
|
||||
if cfg.Server.Host != "127.0.0.1" {
|
||||
t.Fatalf("Server.Host = %q", cfg.Server.Host)
|
||||
}
|
||||
if cfg.Server.Port != 6001 {
|
||||
t.Fatalf("Server.Port = %d, want 6001", cfg.Server.Port)
|
||||
}
|
||||
if cfg.Access.Proxy != "" {
|
||||
t.Fatalf("Access.Proxy = %q, want empty override", cfg.Access.Proxy)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user