Golang如何获取文件所在的目录,而不是当前的工作目录 [英] Golang how to get the directory of the package the file is in, not the current working directory
问题描述
我有一个测试包,我只用它来测试API调用并测试函数的主包,我只是包括
其他包到。
在我正在工作的主包我有
ioutil.ReadFile(filepath.Abs(Filename.pub))
这是可以的,但是当我从我的测试包中调用它时,例如
/ 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 /
这就是它的地方。
只是以澄清这个混乱的话:
API包有一个函数读取来自同一个目录
但是因为我包含API包,并且Testfolder是CWD,所以当我 go run main.go
而是试图从 testfolder
取代它,即使main.go没有该函数并且只包含它。
非常感谢您对这个令人困惑的屁股问题抱歉 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\\\
,filename,path.Dir(filename))
https://开头播放.golang.org / p / vVa2q-Er6D
I'm making a package to make API calls to a service.
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
it tells me
panic: open /Users/####/gocode/src/github.com/testfolder/public.pub: no such file or directory
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:
The API Package has a function that reads from the same directory
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.
Thanks sorry for the confusing ass question
runtime.Caller is what you want I believe.
Here is a demonstration :
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
这篇关于Golang如何获取文件所在的目录,而不是当前的工作目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!