英文:
Relative path in Go
问题
我正在尝试理解Go语言中的相对路径构建。这是我的问题:我有一个文件夹树:
-root
--main
---utils
---certs
--tests
我将我的证书上传到certs文件夹中,并将连接工具util.go
文件上传到utils
文件夹中,我在文件中硬编码了相对路径。
问题:在utils/util.go
中指定的路径在从main/main.go
调用时正常工作,但在从tests/test.go
调用时会抛出异常(文件未找到)。
有什么解决办法?
英文:
I'm trying to understand a relative path building in Go. Here is my problem: I have a folders tree:
-root
--main
---utils
---certs
--tests
Having my certificates uploaded into certs folder and connectivity util.go
file uploaded into utils
, I have relative paths hard coded in the file.
Problem: Having paths specified in utils/util.go
, they work fine once called from main/main.go
and throw exception (file not found) when called from tests/test.go
.
What's the way out?
答案1
得分: 3
使用go/build包来查找Go工作区中包的绝对路径:
import (
"go/build"
"path/filepath"
)
importPath := "github.com/user/root/main" // 修改为main包的导入路径
p, err := build.Default.Import(importPath, "", build.FindOnly)
if err != nil {
// 处理错误
}
certsDir := filepath.Join(p.Dir, "certs")
这只在Go工作区的上下文中运行时有效(源代码可用且已设置GOPATH)。
英文:
Use the go/build package to find the absolute path of a package in a Go workspace:
importPath := "github.com/user/root/main" // modify to match import path of main
p, err := build.Default.Import(importPath, "", build.FindOnly)
if err != nil {
// handle error
}
certsDir := filepath.Join(p.Dir, "certs")
This only works when run in the context of a Go workspace (the source code is available and GOPATH is set).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论