Using go-bindata with with html/template
What is go-bindata and why do we need it?
go-bindata converts any text or binary file into Go source code, which is useful for embedding data into Go programs. So you can build your whole project into 1 binary file for easier delivery.
Let's write some program which will have html template file and build this program in a way that we will need only 1 exutable file to run it.
- Create tpl/page.html
- Create main.go
Let's compile it:
go build -o app
./app
So our program works, now let's see how can we embed template into the Go code.
Generate templates with go-bindata
We need to install go-bindata CLI and generate a .go file from our templates:
go get github.com/jteeuwen/go-bindata/...
go-bindata -o tpl.go tpl
Let's look into tpl.go file, this file was generated by go-bindata and contains byte code of our template and helper functions.
I prefer to add last command to go:generate
:
//go:generate go-bindata -o tpl.go tpl
And use:
go generate
html/template
html/template's function ParseFiles
works only with files on the filesystem, so we can't use this function. What we can use is function Parse
.
Use go-bindata templates
go build -o app
./app
<!DOCTYPE html>
<html lang="en">
<body>
Hello
</body>
</html>
Conclusion
- With
go-bindata
you can simplify your deployment with only one binary file.
go-bindata
can give you a little faster templates reading.
- Note that if you use
ParseFiles
you have to change it to work with Assert
function.