Skip to content
shellhacks.dev
Go

Embed a File in a Go Binary with the go:embed Directive

Compile a file into a Go binary with a go:embed comment above a string, byte slice or embed.FS variable. It needs Go 1.16, and a missing file is a build error.

2 min read
Summarize in AI

A program needs a template or a data file at run time, and you want to ship a single executable.

Shell
export HOME=/tmp
mkdir demo && cd demo
go mod init demo 2> /dev/null
echo 'hello from a file' > greeting.txt
cat > main.go <<'EOF'
package main

import (
	_ "embed"
	"fmt"
)

//go:embed greeting.txt
var greeting string

func main() { fmt.Print(greeting) }
EOF
go build -o app . && rm greeting.txt && ./app
sed -i 's/greeting.txt/missing.txt/' main.go
go build -o app2 .
Text
hello from a file
main.go:8:12: pattern missing.txt: no matching files found

A //go:embed greeting.txt comment directly above a string variable makes the compiler read the file and store its contents in the binary. The blank import of embed is needed for that. The run builds the program, deletes the source file and still prints hello from a file. Pointing the pattern at a file that does not exist stops the build with pattern missing.txt: no matching files found. See the embed package.

The files must be in the package directory or below it, a pattern cannot contain .., and files whose names begin with a dot or with _ are left out of an embedded directory unless the pattern starts with all:. The content is fixed at build time, so a change needs a rebuild. This was run with Go 1.19.

Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.