我有一个具有以下结构的 Go 项目,我正在努力读取位于我的项目中的配置文件,我需要读取 config yaml
(在根项目中),我应该在 sub root directory
下的 other package 中读取它,我得到了 not found
myproject
- config.yaml
- cmd
--com
---ftp
----fs.go
在 fs.go
中,我需要阅读 config.yaml
并且没有成功。我尝试使用 os.Getwd
和 ex, 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 typestring
,[]byte
, orFS
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/