From c421aed9252efcbd34ece744ac583184b6685f74 Mon Sep 17 00:00:00 2001 From: yarnom Date: Tue, 14 Oct 2025 11:57:33 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E6=AD=A3config=E8=B7=AF?= =?UTF-8?q?=E5=BE=84=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/config/config.go | 21 ++++++++++++++++----- internal/tools/exporter.go | 17 +++++++++++++---- 2 files changed, 29 insertions(+), 9 deletions(-) diff --git a/internal/config/config.go b/internal/config/config.go index 7a67669..07f311c 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -84,12 +84,23 @@ func GetConfig() *Config { // loadConfig 从配置文件加载配置 func (c *Config) loadConfig() error { - // 尝试多个位置查找配置文件 + // 尝试多个位置查找配置文件(兼容从仓库根目录、bin目录、系统安装路径运行) + exePath, _ := os.Executable() + exeDir := "" + if exePath != "" { + exeDir = filepath.Dir(exePath) + } configPaths := []string{ - "config.yaml", // 当前目录 - "../config.yaml", // 上级目录 - "../../config.yaml", // 项目根目录 - filepath.Join(os.Getenv("HOME"), ".weatherstation/config.yaml"), // 用户目录 + // 工作目录及其上级 + "config.yaml", + "../config.yaml", + "../../config.yaml", + // 可执行文件所在目录(用于 /opt/weatherstation/bin 场景) + filepath.Join(exeDir, "config.yaml"), + filepath.Join(exeDir, "..", "config.yaml"), + // 系统级与用户级 + "/etc/weatherstation/config.yaml", + filepath.Join(os.Getenv("HOME"), ".weatherstation", "config.yaml"), } var data []byte diff --git a/internal/tools/exporter.go b/internal/tools/exporter.go index 8b67190..fde213c 100644 --- a/internal/tools/exporter.go +++ b/internal/tools/exporter.go @@ -18,6 +18,13 @@ import ( "weatherstation/internal/database" ) +func getenvDefault(key, def string) string { + if v := os.Getenv(key); v != "" { + return v + } + return def +} + // Exporter 负责每10分钟导出 CSV(含ZTD融合) type Exporter struct { pg *sql.DB @@ -47,10 +54,11 @@ func NewExporterWithOptions(opts ExporterOptions) *Exporter { } // 创建导出专用日志文件(追加模式) - if err := os.MkdirAll("export_data", 0o755); err != nil { + outBase := getenvDefault("EXPORT_DIR", "export_data") + if err := os.MkdirAll(outBase, 0o755); err != nil { log.Printf("创建导出日志目录失败: %v", err) } - f, err := os.OpenFile(filepath.Join("export_data", "export.log"), + f, err := os.OpenFile(filepath.Join(outBase, "export.log"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644) if err != nil { log.Printf("创建导出日志文件失败: %v", err) @@ -112,8 +120,9 @@ func (e *Exporter) Start(ctx context.Context) error { // exportBucket 导出一个10分钟桶(CST) func (e *Exporter) exportBucket(ctx context.Context, bucketStart, bucketEnd time.Time) error { utcDay := bucketEnd.UTC().Format("2006-01-02") - outDir := filepath.Join("export_data") - histDir := filepath.Join("export_data", "history") + outBase := getenvDefault("EXPORT_DIR", "export_data") + outDir := filepath.Join(outBase) + histDir := filepath.Join(outBase, "history") if err := os.MkdirAll(histDir, 0o755); err != nil { return err }