如何获取文件所在包的目录,而不是当前工作目录 [英] How to get the directory of the package the file is in, not the current working directory
问题描述
我正在打包程序以对服务进行API调用.
I'm making a package to make API calls to a service.
我有一个测试包,该测试包仅用于测试API调用和测试主包的功能,而我只是将其打包到另一个包中.
I have a test package that I use just to test the API calls and test the functions of the main package which I just include
the other package into.
在我正在处理的主程序包中
In my main package that I'm working on I have
ioutil.ReadFile(filepath.Abs("Filename.pub"))
哪个还可以,但是当我从测试包中调用它时,例如
Which is ok, but when I call it from my test package e.g.
/Users/####/gocode/src/github.com/testfolder go run main.go
它告诉我
panic: open /Users/####/gocode/src/github.com/testfolder/public.pub: no such file or directory
问题是,它正在testfolder
内寻找public.pub
而不是它所在的github.com/apipackage/
.
The problem is, is it is looking for public.pub
inside of testfolder
instead of github.com/apipackage/
which is where it is.
只是为了澄清这种混乱的说法:
Just to clarify this mess of words:
API包具有从同一目录读取的功能
The API Package has a function that reads from the same directory
但是因为我包括了API包,而当我go run main.go
时Testfolder是CWD,所以它试图从testfolder
获取它,即使main.go没有该功能并且只是包括它.
But because I'm including the API package and Testfolder is the CWD when I go run main.go
it is instead trying to get it from the testfolder
instead even though the main.go doesn't have the function and is just including it.
推荐答案
runtime.Caller 是我想要的相信.
这是一个示范:
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
这篇关于如何获取文件所在包的目录,而不是当前工作目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!