From 64423b00e29d93b0f65b2281a898a9f1dae1e9ba Mon Sep 17 00:00:00 2001 From: wood chen Date: Wed, 12 Mar 2025 20:50:19 +0800 Subject: [PATCH] =?UTF-8?q?feat(config):=20=E6=B7=BB=E5=8A=A0=E9=BB=98?= =?UTF-8?q?=E8=AE=A4=E9=85=8D=E7=BD=AE=E6=96=87=E4=BB=B6=E5=88=9B=E5=BB=BA?= =?UTF-8?q?=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 实现 createDefaultConfig 方法,在配置文件不存在时自动创建默认配置 - 移除 config.json 中的固定路径配置 - 支持自动创建配置文件目录 - 提供默认的压缩和路由配置 --- data/config.json | 14 +----------- internal/config/config.go | 46 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 13 deletions(-) diff --git a/data/config.json b/data/config.json index e2061a9..e2e6be0 100644 --- a/data/config.json +++ b/data/config.json @@ -23,17 +23,5 @@ "Enabled": false, "Level": 4 } - }, - "FixedPaths": [ - { - "Path": "/cdnjs", - "TargetHost": "cdnjs.cloudflare.com", - "TargetURL": "https://cdnjs.cloudflare.com" - }, - { - "Path": "/jsdelivr", - "TargetHost": "cdn.jsdelivr.net", - "TargetURL": "https://cdn.jsdelivr.net" - } - ] + } } \ No newline at end of file diff --git a/internal/config/config.go b/internal/config/config.go index f515b38..b0191a8 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -3,6 +3,7 @@ package config import ( "encoding/json" "os" + "strings" "sync" "sync/atomic" "time" @@ -48,10 +49,55 @@ func Load(path string) (*Config, error) { once.Do(func() { instance = &configImpl{} err = instance.reload(path) + // 如果文件不存在,创建默认配置并重新加载 + if err != nil && os.IsNotExist(err) { + if createErr := createDefaultConfig(path); createErr == nil { + err = instance.reload(path) + } else { + err = createErr + } + } }) return &instance.Config, err } +// createDefaultConfig 创建默认配置文件 +func createDefaultConfig(path string) error { + // 创建目录(如果不存在) + dir := path[:strings.LastIndex(path, "/")] + if err := os.MkdirAll(dir, 0755); err != nil { + return err + } + + // 创建默认配置 + defaultConfig := Config{ + MAP: map[string]PathConfig{ + "/": { + DefaultTarget: "http://localhost:8080", + }, + }, + Compression: CompressionConfig{ + Gzip: CompressorConfig{ + Enabled: true, + Level: 6, + }, + Brotli: CompressorConfig{ + Enabled: true, + Level: 6, + }, + }, + } + + // 序列化为JSON + data, err := json.MarshalIndent(defaultConfig, "", " ") + if err != nil { + return err + } + + // 写入文件 + return os.WriteFile(path, data, 0644) +} + // RegisterUpdateCallback 注册配置更新回调函数 func RegisterUpdateCallback(callback func(*Config)) { callbackMutex.Lock()