Go by Example: Embed Directive
Go 1.23
Embed static files and assets directly into your Go binary. This example demonstrates using the `//go:embed` directive to include files as strings, byte slices, or a virtual filesystem.
Code
package main
import (
"embed"
"fmt"
)
// Embed a single file as a string
//go:embed folder/single_file.txt
var fileString string
// Embed a single file as a byte slice
//go:embed folder/single_file.txt
var fileByte []byte
// Embed multiple files/directories into a filesystem
//go:embed folder/*.txt
var folder embed.FS
func main() {
// Print the embedded string
fmt.Print(fileString)
// Print the embedded byte slice
fmt.Print(string(fileByte))
// Read from the embedded filesystem
content, _ := folder.ReadFile("folder/file1.txt")
fmt.Print(string(content))
}Explanation
The //go:embed directive (introduced in Go 1.16) allows you to embed static assets—such as HTML templates, SQL migration scripts, images, or configuration files—directly into your compiled Go binary. This creates a self-contained executable that doesn't rely on external files at runtime, significantly simplifying deployment and distribution.
To use embedding, you must import the embed package (use _ "embed" if you don't use the package explicitly). The directive is placed immediately above a variable declaration and supports three types:
- string: Best for text files. The file content is available as a read-only string.
- []byte: Best for binary files (images, etc.). The content is available as a byte slice.
- embed.FS: Best for multiple files or directories. It creates a read-only virtual filesystem that implements
fs.FS, allowing you to traverse directories and open files programmatically.
Code Breakdown
4
Importing the "embed" package is mandatory to use the //go:embed directive. If you aren't using the embed.FS type explicitly, you can use a blank import: _ "embed".
9
The //go:embed directive. It MUST be a comment starting with "//go:embed" (no space after //) and placed immediately before the variable declaration. It tells the compiler to load "folder/single_file.txt" into "fileString".
10
Embedding into a string variable. The file content is read at compile time and stored in the binary. This variable will hold the file's text content at runtime.
18
Embedding multiple files into an embed.FS. The pattern "folder/*.txt" matches all text files in the folder. embed.FS is a read-only virtual filesystem that preserves the directory structure.
28
Accessing files from the embedded filesystem using folder.ReadFile(). This works just like reading from a real disk, but it reads from the binary's embedded data.

