Context
I created a simple program to auto update my Public IP address on OpenDNS. To be able to use the program I need the credentials for OpenDNS site, so I created a config.json file to be able to read the credentials from it.
Inside the Go project folder, calling the binary, works fine
./main
http return code: 200 defining the new IP: 123.123.123.123
If I change to another folder (let's say my /home/user for example), the binary can't open the file anymore
./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
I'm opening the file the following way:
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
}
Why do I want to call my binary from another folder?
Because I want this program to be executed by cronjob every 5 minutes.