Embed Directive
Use //go:embed to bundle a file into a string, byte slice, or embed.FS at build time.
The //go:embed directive copies files into a binary at build time. Put the directive immediately before a string, byte slice, or embed.FS variable.
This example expects greeting.txt beside the Go source file. The embedded string is available when the program runs, without opening a separate disk file.
package main
import (
_ "embed"
"fmt"
)
//go:embed greeting.txt
var greeting string
func main() {
fmt.Print(greeting)
}In production
Embedded data is read-only and increases the binary size. embed.FS implements fs.FS, so it works with APIs such as template.ParseFS that accept that interface. Embed only files that belong in the deployed binary.
Enjoyed this? Get more software craft delivered to your inbox.