Tip: GO embed for content and build

I’ve received some helpful advice recently and thought I’d share back.

I’ve been deploying GO apps here recently and have been using the new GO embed package. It works well and does exactly what I want. I have middleware for DEV that reloads templates on each page load. I’m very happy with it.

I also use embed for build information. My deploy batch file writes a TOML file with the git information and current build date – and anything else I want to embed.

git = "v0.0.8-3-g7efdf60"
built = "2021-06-10T07:03:26-05:00"

That TOML file is “embedded” in the application:

//go:embed other/build.toml
var configFile string

// Build holds the embedded build information from the TOML file
type Build struct {
	Git   string    `toml:"git"`
	Built time.Time `toml:"built"`

A simple TOML file like this is really just key-value which is easy to write. I use PowerShell as I’m on Windows.

Bonus Tip: Formerly, I used .html or .tmpl as the extension for my HTML templates. I recently switched to .gohtml when I discovered a VSCode extension that did better syntax highlighting for the template language: casualjim/vscode-gotemplate (github.com). It actually supports lots of file extensions but I didn’t know that at the time. A small change but it helps the ergonomics :slight_smile:

Thanks for a great environment. I’m very happy with your service so far.

I hadn’t thought about using embed before. That’s an interesting suggestion. I usually use -X with ldflags to inject values into variables in the binary. For example, if I have a main package file:

package main

var Version string

func main() { ... }

Then I can set the variable at compile-time like this:

go build -ldflags "-X 'main.Version=v1.0.0'" .
1 Like