This question already has an answer here:
How to get the directory of the package the file is in, not the current working directory

(1个答案)


去年关闭。




我在回购中有一个包含静态文件的软件包。
myPackage
static/sample.json
main.go
main.go使用os.Open('static/sample.json")并处理文件

然后,我有另一个回购,它通过导入来使用mypackage。问题是它正在这个新仓库中寻找json文件。我试图放置完整路径github.com/username/mypackage/static/sample.json,但仍然找不到。有什么办法可以将文件保留在另一个软件包中?

最佳答案

从这个问题answer here

_, filename, _, ok := runtime.Caller(0)

if !ok {
    panic("no caller information")
}

os.Open(path.Dir(filename) + '/static/sample.json")

做到了。

关于go - 如何确定软件包源文件的目录,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55562632/

10-14 16:30
查看更多