英文:
How to reliably refer to static file in a Go application?
问题
我正在编写一个基于模板生成文件的Go命令行工具。
这些模板与命令行工具的代码一起位于Git仓库中。
我希望实现以下功能:
- 无论从哪里调用二进制文件,它都应该能够找到模板目录。
- 如果需要,用户可以覆盖模板目录。
由于这是一个Go应用程序,我采用了以下方法:
templateRoot := filepath.Join(
os.Getenv("GOPATH"),
"src/github.com/myuser/myproject/templates",
)
但作为一个相对新手,我想知道这种方法是否足够可靠:我的应用程序模板是否保证始终可以在该路径下访问?
如果有人将我的应用程序作为供应商引入到他们自己的项目中,会怎么样?对于一个命令行工具来说,这样做有意义吗?
由于第2点的原因,我显然不能使用go-bindata,因为我希望允许模板被覆盖。
总结一下:在Go命令行工具中,如何可靠地引用非Go静态文件的策略是什么?
英文:
I am writing a Go command-line tool that generates some files based on templates.
The templates are located in the Git repository alongside the code for the command-line tool itself.
I wanted to allow the following:
- The binary, wherever it is called from, should always find the templates directory.
- The templates directory can be overriden by the user if need be.
Since this is a Go application, I went with something like:
templateRoot := filepath.Join(
os.Getenv("GOPATH"),
"src/github.com/myuser/myproject/templates",
)
But being rather new to Go, I wonder if this approach is reliable enough: is it guaranteed that my application template will always be accessible at that path ?
What if someone vendorize my application into their own project ? Does that even make sense for a command-line tool ?
Because of 2., I obviously can't/won't use go-bindata because I want to allow for the templates to be overriden if need be.
In summary: what is a good strategy to reliably refer to non-go, static files in a Go command-line tool ?
答案1
得分: 1
GOPATH
用于构建应用程序。虽然你可以在运行时查找 GOPATH
并检查每个 GOPATH
条目的相对位置,但不能确定它是否存在(除非你将其作为运行应用程序的先决条件)。
go get
本身是为开发人员提供的一种方便的方式来获取和构建 Go 包。它依赖于具有 GOPATH
(尽管在 go1.8 中有一个默认值)和 GOBIN
的 PATH
。许多程序需要额外的步骤,这些步骤不在简单的 go
工具的范围内,并且有脚本或 Makefile 来进行构建。如果你的目标用户不是开发人员,你需要提供一种安装到标准系统路径的方式。
像任何常规程序一样,使用一些众所周知的路径来定位模板文件。你可以在你的程序中添加一些逻辑,检查一系列位置:相对于 $GOPATH
,相对于二进制文件,工作目录,$HOME
等等;只需向用户提供一个你的程序将查找模板的位置列表即可。
英文:
GOPATH
is used for building the application. While you could look for GOPATH
and check relative locations to each GOPATH
entry at runtime, you can't be sure it will exist (unless of course you make it a prerequisite for running your application).
go get
itself is a convenience for developers to fetch and build a go package. It relies on having a GOPATH
(though there's a default now in go1.8), and GOBIN
in your PATH
. Many programs require extra steps not covered by the simple go
tool, and have scripts or Makefiles to do the build. If you're targeting users that aren't developers, you need to provide a way to install into standard system paths anyway.
Do what any regular program would do, and use some well-known path to locate the template files. You can certainly add some logic in your program to check for a hierarchy of locations: relative to $GOPATH
, relative to the binary, working directory, $HOME
, etc; just provide a list of locations to the user that your program will look for templates.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论