Relative path in Go

huangapple go评论159阅读模式
英文:

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

huangapple
  • 本文由 发表于 2016年4月25日 22:14:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/36843144.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定