gpt4 book ai didi

go - Go 中的相对路径

转载 作者:IT王子 更新时间:2023-10-29 01:45:21 27 4
gpt4 key购买 nike

我试图了解 Go 中的相对路径构建。这是我的问题:我有一个文件夹树:

-root
--main
---utils
---certs
--tests

将我的证书上传到 certs 文件夹并将连接 util.go 文件上传到 utils,我在文件中硬编码了相对路径。

问题:在 utils/util.go 中指定了路径,一旦从 main/main.go 调用它们就可以正常工作,并在调用时抛出异常(找不到文件)来自 tests/test.go

出路在哪里?

最佳答案

使用 go/build package 在 Go 工作空间中查找包的绝对路径:

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")

这仅在 Go 工作区的上下文中运行时有效(源代码可用且 GOPATH 已设置)。

关于go - Go 中的相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36843144/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com