现在我runtime.Caller(0)结合使用path.Dir和filepath.Abs来获取当前执行文件的路径并获取相对于它的项目根目录。
所以假设我有一个这样的文件夹结构:
$GOPATH/src/example.org/myproject
$GOPATH/src/example.org/myproject/main.go
$GOPATH/src/example.org/myproject/path
$GOPATH/src/example.org/myproject/path/loader.go
Run Code Online (Sandbox Code Playgroud)
如果我想要我的项目根目录,我调用 loader.go ,它依次获取其路径,runtime.Caller(0)然后上升一个文件夹以到达项目根目录。
问题是当使用go test -cover执行的文件不再在其正常位置时,而是在用于测试和覆盖率分析的特殊子目录中。
runtime.Caller(0)给我以下内容:
example.org/myproject/path/_test/_obj_/loader.go
Run Code Online (Sandbox Code Playgroud)
运行它path.Dir,filepath.Abs会给我:
$GOPATH/src/example.org/myproject/path/example.org/myproject/path/_test/_obj_
Run Code Online (Sandbox Code Playgroud)
当我从那里上去时,我不会到达项目根目录,但显然完全不同。所以我的问题
是:有没有可靠的方法来获得项目根?
您可以从环境变量构建它$GOPATH:
gp := os.Getenv("GOPATH")
ap := path.Join(gp, "src/example.org/myproject")
fmt.Println(ap)
Run Code Online (Sandbox Code Playgroud)
这将产生您的项目目录的绝对路径:
/path/to/gopath/src/example.org/myproject
GOPATH这显然只有在设置时才有效。又名。在你的开发机器上。在生产中,您需要通过配置文件提供目录。