Golang how to get the package directory where the file is located and not the current working directory

I am making a package to call API calls for a service.

I have a test package that I use only to test API calls and test the functions of the main package, which I just include on another package.

In my main package I'm working on, I

ioutil.ReadFile(filepath.Abs("Filename.pub"))

This is normal, but when I call it from my test suite, for example.

/Users/####/gocode/src/github.com/testfolder go run main.go

he tells me

panic: open /Users/####/gocode/src/github.com/testfolder/public.pub: no such file or directory

The problem is that it is looking for public.pub inside the testfolder instead of github.com/apipackage/ where it is located.

Just to clear up this mess of words:

The API package has a function that reads from the same directory

But since I include the API package, and Testfolder is CWD, when I go run main.go instead of trying to get it from testfolder , even if main.go has no function and just turning it on.

Thank you, sorry for the confusing contentious issue.

+6
source share
1 answer

runtime.Caller is what you want, I believe.

Here is a demo:

 package main import ( "fmt" "runtime" "path" ) func main() { _, filename, _, ok := runtime.Caller(0) if !ok { panic("No caller information") } fmt.Printf("Filename : %q, Dir : %q\n", filename, path.Dir(filename)) } 

https://play.golang.org/p/vVa2q-Er6D

+15
source

All Articles