語境
我創建了一個簡單的程式來自動更新我在 OpenDNS 上的公共 IP 地址。為了能夠使用該程式,我需要 OpenDNS 站點的憑據,因此我創建了一個 config.json 檔案以便能夠從中讀取憑據。
在 Go 專案檔案夾中,呼叫二進制檔案,作業正常
./main
http return code: 200 defining the new IP: 123.123.123.123
如果我更改到另一個檔案夾(例如我的 /home/user),二進制檔案將無法再打開該檔案
./Documents/ip-updater-opendns/main
panic: couldn't open config file config.json: open config.json: no such file or directory
goroutine 1 [running]:
main.loadConfigFile()
/home/user/Documents/ip-updater-opendns/main.go:50 0x1e6
main.main()
/home/user/Documents/ip-updater-opendns/main.go:25 0x45
我正在通過以下方式打開檔案:
func loadConfigFile() Config {
const ConfigFileEnv = "config.json"
var config Config
file, err := os.Open(ConfigFileEnv)
if err != nil {
panic(fmt.Errorf("couldn't open config file %s: %w", ConfigFileEnv, err))
}
err = json.NewDecoder(file).Decode(&config)
if err != nil {
panic(fmt.Errorf("couldn't decode config file %s as Json: %w", ConfigFileEnv, err))
}
return config
}
為什么我想從另一個檔案夾呼叫我的二進制檔案?
因為我希望這個程式每5分鐘被cronjob執行一次。
所以我的問題是,如何解決這個問題?
uj5u.com熱心網友回復:
當您在 go 專案中運行時,config.json位于當前目錄中,因此相對路徑config.json有效。當您從其他目錄運行時,這不再正確,并且config.json無法找到。
const ConfigFileEnv = "config.json"
您對組態檔名進行了硬編碼,因此它必須位于您當前的作業目錄中。為什么不將組態檔的名稱放在程式的引數中?
if len(os.Args) < 1 {
panic("First argument should be config file path")
}
var ConfigFileEnv = os.Args[1]
當您從專案目錄運行它時,您可以使用相對路徑:
./main config.json
當您從不同的目錄(或您的 cron)運行它時,您可以使用相對于主目錄的不同路徑:
Documents/ip-updater-opendns/main Documents/ip-updater-opendns/config.json
(請注意,./在路徑前添加1 次或多次是多余的。相對路徑始終相對于.當前作業目錄)。
另一種方法是讓 cron 作業在執行程式之前更改 shell 中的目錄:
*/5 * * * * bash -c "cd Documents/ip-updater-opendns/; exec ./main"
但我不會那樣做。我質疑硬編碼組態檔名的價值。強加只能config.json從當前目錄讀取的限制是沒有意義的。我會將它作為引數或環境變數傳遞。那么如果你碰巧有多個 OpenDNS 域名,你也可以配置多個不同的組態檔。
進一步考慮這一點,將其config.json放入您的專案目錄真的很有意義嗎?將它放在其他地方可能更有意義,例如~/.opendns-config.json或在某處/var。一旦編譯了 go 程式,專案目錄就變得無關緊要了。我可能會把main像/usr/local/bin/我這樣的地方- 并命名為比main- 也許opendns-update或類似的東西。然后 cron 看起來像:
*/5 * * * * opendns-update /home/LUCAS.VARELA/.opendns-config.json
您可能還想看看go install 有什么作用?這解釋了您如何go install為您的專案作業,這將進一步區分開發專案及其在“生產”中的使用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/335649.html
