Embedding files with go:embed
- Version
- 1.27
- Since
- 1.16
- Review
- Draft
Summary#
A //go:embed directive stores file contents in the compiled program. Put it above a package-level variable of type string, []byte or embed.FS. Patterns are relative to the source file's package directory.
Syntax#
import "embed" // use a blank import if embedding only strings or byte slices
//go:embed version.txt
var version string
//go:embed templates/*.txt
var templates embed.FS
Example#
In an empty temporary directory, run go mod init example. Save the code as main.go there, then run go run ..
package main
import (
"embed"
"errors"
"fmt"
"io/fs"
"strings"
)
//go:embed go.mod
var moduleText string
//go:embed go.mod
var files embed.FS
func main() {
firstLine, _, _ := strings.Cut(moduleText, "\n")
fmt.Println(firstLine)
entries, err := files.ReadDir(".")
if err != nil {
fmt.Println(err)
return
}
for _, entry := range entries {
fmt.Println("embedded:", entry.Name())
}
data, err := files.ReadFile("go.mod")
fmt.Println(string(data) == moduleText, err)
_, err = files.ReadFile("missing.txt")
fmt.Println(errors.Is(err, fs.ErrNotExist))
}
Expected output#
The example embeds the generated go.mod. Its content is fixed at build time.
module example
embedded: go.mod
true <nil>
true
Common mistakes#
The directive does not work on local variables. A pattern that matches nothing fails the build, and patterns cannot contain ... Embedding a directory by name skips files that start with . or _; prefix the pattern with all: to include them.
Version applicability#
Go 1.16 added //go:embed and the embed package. Earlier versions generate Go source from assets or read the files at run time. The example also uses strings.Cut and requires Go 1.18 or later.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0