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?
Depending on whether you use
go install <your_package>
orgo 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 rungo build <your_package>
in the folder that contains yourmain.go
andconfig.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 yourioutil.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.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.
Approach #1: Command-line argument
Use the
flag
package to pass the path to your config file as a command-line flag:Start the application with
./application -config=/path/to/config.json
(depends on your platform).Approach #2: Environment variable
Use the
os
package to read the path from your system environment.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.