I have a Go application using a config.json
file to get some information. When doing a go run main.go
it works but when I'm compiling the application into an executable I have the error open config.json: no such file or directory
.
My code is:
func main() {
data, err := ioutil.ReadFile("./config.json")
check(err)
var config config
err = json.Unmarshal(data, &config)
check(err)
}
I also have tried ioutil.ReadFile("config.json")
and it does not work. check(err)
and the config
structure are in the main.go
, the problem does not come from here.
main.go
, config.json
and the executable are in the same directory.
What should I do to be able to use the config.json
file once the program is compiled?
Your config file is probably not in the working directory you have started your application in. But hardcoding the path to the file is not the best of practices.
Use the flag
package to pass the path to your config file as a command-line flag:
var filename = flag.String("config", "config.json", "Location of the config file.")
func main() {
flag.Parse()
data, err := ioutil.ReadFile(*filename)
check(err)
var config config
err = json.Unmarshal(data, &config)
check(err)
}
Start the application with ./application -config=/path/to/config.json
(depends on your platform).
Use the os
package to read the path from your system environment.
func main() {
filename := os.Getenv("PATH_TO_CONFIG")
if filename == "" {
filename = "config.json"
}
data, err := ioutil.ReadFile(filename)
check(err)
var config config
err = json.Unmarshal(data, &config)
check(err)
}
Set the environment variable export PATH_TO_CONFIG=/path/to/config.json
(depends on your platform) and start the application.
Both approaches will attempt to find config.json
in the working directory if no path was provided to the application.
Depending on whether you use go install <your_package>
or go build <your_package>
, your final executable will end up in different location.
If you are using go build <your_package>
, your executable will be located in the folder where you invoked the command. IOW, it will likely work if your run go build <your_package>
in the folder that contains your main.go
and config.json
.
If you use go install <your_package>
, your executable will be located in your $GOPATH/bin
. In that case, you will have to update the argument to your ioutil.ReadFile()
function call accordingly.
The better approach is to pass the file location of your config.json
as an argument to your executable, instead of hard-coding it.