embed

Guided tour · I/O & Files · pkg.go.dev →

Embed files and directories into your binary at build time. No external assets at runtime.

The three forms

Embed a single file as a string

import _ "embed"

//go:embed version.txt
var version string

fmt.Println(version)

Embed as []byte — binary assets

//go:embed logo.png
var logo []byte

Embed a tree as embed.FS — io/fs.FS compatible

Pass to http.FileServerFS, template.ParseFS, fs.Sub, fs.WalkDir — anywhere that takes an fs.FS.

import "embed"

//go:embed templates static
var assets embed.FS

tmpl := template.Must(template.ParseFS(assets, "templates/*.html"))

static, _ := fs.Sub(assets, "static")
mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServerFS(static)))

Patterns and gotchas

Multiple patterns

//go:embed *.sql migrations/*
var schema embed.FS

The directive must be on a package-level var

The line just above the var must be the //go:embed directive. No blank line between them.

Hidden files excluded by default

Files/dirs starting with . or _ are ignored. Use all: prefix to include them: //go:embed all:assets.