Embed Static Assets Into Binary

Ship templates and static files inside the binary with go:embed so deployment is one artifact and assets cannot drift from code.

GoConfig Management

Code

gosnippet
23 lines
package main

import (
	"embed"
	"fmt"
)

//go:embed version.txt
var versionFile string

//go:embed templates/*.tmpl
var templateFS embed.FS

func main() {
	fmt.Println("version:", versionFile)

	data, err := templateFS.ReadFile("templates/greeting.tmpl")
	if err != nil {
		fmt.Println("missing template:", err)
		return
	}
	fmt.Println("template bytes:", len(data))
}

What the code does

Embed Static Assets Into Binary reduces to the function main.

Nothing falls through silently — 1 checkpoint test err != nil on the way through.

What to watch for

  • Everything it calls is documented as part of the language core.

Applying it

The run emits 3 labeled sections — version:, missing template:, template bytes: — one per step.

Statements that decide the outcome

if err != nil {
fmt.Println("missing template:", err)
return
}

Interactive Tools for This Topic

FAQ

What does Embed Static Assets Into Binary print when run?
Execute the whole file; each printed line is prefixed with a label like `version:`, `missing template:`, `template bytes:`.