You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go开发的OpenDNS IP更新程序跨路径执行无法读取config.json如何解决

问题原因

你当前代码使用相对路径config.json读取配置,相对路径的基准是程序运行时的当前工作目录,不是二进制文件存放的目录。切换目录执行时程序会从你所处的目录下找配置文件,自然会报错找不到文件。

解决方案

方案1:无需改代码,直接调整cron任务写法(最快生效)

cron任务执行时先切换到二进制所在目录再执行程序即可,定时任务规则写为:

*/5 * * * * cd /home/user/Documents/ip-updater-opendns && ./main

方案2:修改代码默认读取二进制同目录的配置文件(推荐,适配任意路径调用)

通过os.Executable()获取二进制文件自身的绝对路径,再拼接同目录下的config.json路径,修改后的loadConfigFile代码如下:

import (
    "os"
    "path/filepath"
    "fmt"
    "encoding/json"
)

func loadConfigFile() Config {
    // 获取二进制可执行文件的路径
    execPath, err := os.Executable()
    if err != nil {
        panic(fmt.Errorf("failed to get executable path: %w", err))
    }
    // 处理软链接情况,获取真实路径
    execPath, err = filepath.EvalSymlinks(execPath)
    if err != nil {
        panic(fmt.Errorf("failed to evaluate symlinks for executable: %w", err))
    }
    // 取二进制文件所在目录,拼接配置文件名
    configPath := filepath.Join(filepath.Dir(execPath), "config.json")
    
    var config Config
    file, err := os.Open(configPath)
    if err != nil {
        panic(fmt.Errorf("couldn't open config file %s: %w", configPath, err))
    }
    defer file.Close() // 补充原代码缺失的文件关闭逻辑

    err = json.NewDecoder(file).Decode(&config)
    if err != nil {
        panic(fmt.Errorf("couldn't decode config file %s as Json: %w", configPath, err))
    }

    return config
}

修改后不管在哪个目录调用二进制,程序都会去自己存放的目录下找配置文件,完美适配cron定时任务场景。

方案3:支持启动参数指定配置文件路径(更灵活)

如果需要把配置文件放在其他位置,可以新增启动参数指定配置路径,示例代码:

import "flag"

func main() {
    configPath := flag.String("config", "config.json", "path to config file")
    flag.Parse()
    // 后续读取配置时使用*configPath作为路径即可
}

cron任务可以写为:

*/5 * * * * /home/user/Documents/ip-updater-opendns/main --config /etc/ip-updater/config.json

内容的提问来源于stack exchange,提问作者lucasgrvarela

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 15:15:03