Embedding Files in Go Binaries
Start with Embedding Files in Go Binaries
Learn embedding files in go binaries through an executable example, then connect the small demonstration to production code.
What you’ll learn
- Explain the main purpose of embedding files in go binaries.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
The embed package can include files in a compiled binary using //go:embed. This is useful for static templates, migrations or assets shipped with the executable.
A one-file runnable example uses fstest.MapFS to introduce the same fs.FS reading interface; real embedding needs an additional file at build time.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Tools, syntax and practical notes
Real file embedding
package main
import (
"embed"
"fmt"
)
//go:embed assets/message.txt
var assets embed.FS
func main() {
data, err := assets.ReadFile("assets/message.txt")
if err != nil { panic(err) }
fmt.Println(string(data))
}Create assets/message.txt beside main.go in the module before running this version.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"fmt"
"io/fs"
"testing/fstest"
)
func main() {
files := fstest.MapFS{"message.txt": &fstest.MapFile{Data: []byte("Welcome, Go!")}}
data, err := fs.ReadFile(files, "message.txt")
if err != nil {
panic(err)
}
fmt.Println(string(data))
}
Output
Welcome, Go!Trace what the program does
The in-memory MapFS supplies message.txt, and fs.ReadFile reads its bytes. Both MapFS and embed.FS implement the filesystem abstraction used by fs.ReadFile.
Avoid common mistakes
- A //go:embed pattern must match files available at build time.
- Embedding large or sensitive files increases binary size and may expose their bytes to anyone holding the binary.
Try it yourself
Create assets/message.txt and replace MapFS with the embed.FS example below.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Embedding Files in Go Binaries in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.