If my go program can be executed in different ways (cron, monit, etc.), what is the most reliable way to get the directory containing the executable at runtime?
In python, this will be a variable:
os.path.realpath(__file__)
This is probably the same as in C, in other words, there is no portable error checking method. See How to find the location of an executable in C?
One quick fix in go (not necessarily universal) is suggested by Andrew Brookins in the Go To section : How to get the directory of the current file ":
runtime.Caller().goroutines, ..:
runtime.Caller().goroutines, .
runtime.Caller()
.:
_, filename, _, _ := runtime.Caller(1) f, err := os.Open(path.Join(path.Dir(filename), "data.csv"))
The best way I've found is to use os.Getwd(). See the documentation here: golang doc
os.Getwd()