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.
Code
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
Binary Text ConverterConvert UTF-8 text to 8-bit binary groups and decode binary back to text with strict validation.Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.