D
D
Dmitry Shnyrev2014-11-07 21:49:35
go
Dmitry Shnyrev, 2014-11-07 21:49:35

How to get the absolute path of a running program in Go?

Hello. Faced such an interesting problem and I can not find the answer to such a simple question in the internet. Or rather, I found it, but it does not work for me.
The point is to get the absolute path to the running server in order to load the config.json file that lies nearby.
Here is the code itself:

rootDir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
glog.Infoln("rootDir:", rootDir)

but for go run server.go it gives me not the current source folder, but a temporary folder where it is compiled:
/tmp/go-build880064735/command-line-arguments/_obj/exe
And I noticed that if you run the server under gin, then everything is fine and the path is returned correct.
I understand that this is normal behavior (temporary compilation by go run somewhere in the background), but how do they generally act in such cases so as not to hardcode?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
neolink, 2014-11-07
@dmnBrest

my build goes through make (go build is always done, then the compiled binary is launched), and the path to the config is passed through parameters (flags)
as an option, you can look in several places, and add os.Getwd() to rootDir

A
Anton Taraev, 2014-11-12
@ataraev

bitbucket.org/kardianos/osext
folder, _ := osext.ExecutableFolder()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question