go - 在运行时获取项目根路径以读取配置文件

标签 go path

我有一个具有以下结构的 Go 项目,我正在努力读取位于我的项目中的配置文件,我需要读取 config yaml(在根项目中),我应该在 sub root directory 下的 other package 中读取它,我得到了 not found

的错误
myproject
- config.yaml
- cmd
 --com
  ---ftp
   ----fs.go

fs.go 中,我需要阅读 config.yaml 并且没有成功。我尝试使用 os.Getwdex, err := os.Executable() 以及 "../../../" 没有成功,有什么想法吗?

@VonC - 建议使用 https://github.com/gobuffalo/packr 我猜这可以帮助但问题是我需要在 fs.go 中调用它 文件,我需要将其作为参数 main.go 文件传递​​,是否有更好的方法?因为我需要在很多函数中传递这个参数...

viper 有帮助吗? https://github.com/spf13/viper

我的程序是CLI 程序,它将用作bin

最佳答案

2018:如果二进制文件是在 GOPATH/bin 中构建的,而您的源代码在 GOPATH/src 中,那么相对路径将是(在运行时)../src/myproject.

但更简洁的方法是将该文件嵌入到您的二进制文件中。
参见例如 gobuffalo/packr .


2021 年第一季度更新:使用 Go 1.16,您将使用 embed package

Go source files that import "embed" can use the //go:embed directive to initialize a variable of type string, []byte, or FS with the contents of files read from the package directory or subdirectories at compile time.

//go:embed hello.txt
var f embed.FS
data, _ := f.ReadFile("hello.txt")
print(string(data))

关于go - 在运行时获取项目根路径以读取配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51916675/

相关文章:

go - 在golang中获取/设置mp3文件的封面

javascript - 如何呈现带有链接但没有其他 html 的用户帖子?

go - 在 Go 中将 varName 变暗为 int64?

Golang 依赖管理最佳实践

macos - 从 OS X 文件引用 URL 别名获取路径(文件 :///. file/id=...)

java - 错误 : illegal escape character - when trying to create a path

go - 存储通用函数

c# - 无法访问在后端项目中上传的图片

c++ - 在 mac 上编译 hello world wxWidget 程序时找不到 'wx/wx.h' 文件

Java - 在距离加权 map 中找到两点之间的最短路径