Jay
Jay

Reputation: 20156

Including template/html files in your go binary

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.

Upvotes: 16

Views: 16090

Answers (4)

Michael Banzon
Michael Banzon

Reputation: 4967

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.

Upvotes: 10

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93511

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

Upvotes: 16

ShawnMilo
ShawnMilo

Reputation: 6205

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.

Upvotes: 2

steevee
steevee

Reputation: 2588

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

https://github.com/gobuffalo/packr

Upvotes: 4

Related Questions