将模板/HTML文件包含在您的Go二进制文件中

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

Including template/html files in your go binary

问题

我喜欢Go语言内置的模板库,目前我只是将模板声明为常量字符串。通常,如何包含更大更复杂的模板文件呢?理想情况下,我希望它们能够包含在二进制文件中,以简化部署过程。

英文:

Loving Go's built-in template libraries, currently I am just declaring the template as const string. How does one normally go about including larger more sophisticated template files? Ideally I prefer them to be inside the binary to simplify deployment.

答案1

得分: 13

在2021年,随着Go 1.16的发布,将静态文件嵌入代码中变得更加容易。新版本引入了一个名为embed的包,该包提供了一组方便的接口和方法,用于将静态文件附加到Go二进制文件中。

go version
# 1.16.x

# 然后
go doc embed

cks-cli软件中的示例

英文:

Embedding static files in 2021 has become a bit easier since the release of Go 1.16. The new release comes with a new package embed which provides a handy set of interface and methods to attach static file in go binaries

go version
# 1.16.x

# then
go doc embed

example in cks-cli software

答案2

得分: 10

在Go语言中,历史上没有一种标准的方法来实现这一点。出于历史原因,保留了这个答案。请参阅下面的更新答案。

--

正如评论所示,有一些可用的库可以帮助您将二进制数据(如模板、图像等)转换为可以与您自己的源文件一起编译成最终二进制文件的Go源文件。

尽管这种方法适用于许多项目,但我建议您重新考虑。方便分发的代价是,在编译主源代码之前,您必须重新生成创建资产的源文件,并且当您想要分发以这种方式包含的模板/ JavaScript/图像等的微小更改时,您将不得不重新编译和重新启动整个服务器。

在我参与的大多数项目中,前端内容的更改是最常见的更改类型,这导致我们放弃了这种做法。

英文:

Historically there was no standard way to do this in Go. This answer is preserved for historical reasons. See below for updated answer.

--

As comments show there is a few libraries available that will help you transform binary data (like templates, images eg.) to Go source files that can be compiled with your own source files to the final binary.

Although this approach works for many projects I will recommend you reconsider. The cost of having easy distribution is that you must re-generate the source files creating assets before compiling the main source code and when you want to distribute a minor change to the templates/javascript/images&eg. included this way you will have to re-compile and restart the whole server.

On most projects I've worked on changes in frontend stuff is by far the most frequent kind of change - which caused us to move away from this practice.

答案3

得分: 4

packr类似于go-bindata,但是它正在积极维护,甚至可能更容易使用:

https://github.com/gobuffalo/packr

英文:

packr is similar to go-bindata, but actively maintained and maybe even a little nicer to use:

https://github.com/gobuffalo/packr

答案4

得分: 2

这是一个满足需求并防止mbazon所描述的困难的解决方案:

https://godoc.org/github.com/go-bindata/go-bindata

它编译成二进制文件,但在“调试”模式下,它直接从磁盘读取静态资源。

英文:

Here's a solution that fulfills the need and prevents the hardship described by mbazon:

https://godoc.org/github.com/go-bindata/go-bindata

It compiles to binary, but when you're in "debug" mode, it reads your static assets directly from the disk.

huangapple
  • 本文由 发表于 2014年5月18日 20:03:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/23721667.html
匿名

发表评论

匿名网友

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

确定