Go: How to Get the Directory of the Current File[web search]
Go: How to Get the Directory of the Current File
In Python I often use the
__file__ constant to get the directory of the current file (e.g.,
os.path.dirname(os.path.realpath(__file__))). While writing a Go app recently, I found that there wasn’t an immediately obvious (or searchable, even with “golang”) equivalent.
But in the annals of the golong-nuts mailing list I eventually found out about
runtime.Caller(). This returns a few details about the current goroutine’s stack, including the file path.
The context of my problem was opening a data file in a shared package. What I cooked up was:
runtime.Caller identifies the caller of
runtime.Caller as the stack frame to return details about. So you you get info about the file your method is in. Check the docs for more in-depth coverage.
It’s not quite as elegant as
__file__ but it works.