Embed static assets
Embed static assets
Go embed includes files in the compiled program. Place a file named message.txt containing exactly hello (no newline) next to main.go. A //go:embed directive immediately before a package-level string or []byte variable, with the embed import, initializes the variable from the file at build time. Run go run main.go in that folder.
package main
import ( _ "embed" "fmt")
//go:embed message.txtvar message string
func main() { fmt.Println(message)}The blank import _ "embed" is required when the package name is not otherwise used. The file must exist when building. Editing it after compilation does not update the binary; rebuild. Never embed secrets, because anyone with the binary may extract its contents.
Expected output:
helloUse a read-only embedded filesystem
package main
import ( "embed" "fmt" "io/fs")
//go:embed message.txtvar assets embed.FS
func main() { b, e := fs.ReadFile(assets, "message.txt") if e != nil { panic(e) } fmt.Println(string(b))}embed.FS implements fs.FS and can contain multiple matching files. Its paths are slash-separated relative to the source package. Patterns must match valid embeddable files; do not use .. to reach outside the package. This example needs the same message.txt fixture.
Expected output:
helloTry it locally
With the same message.txt, embed it as []byte and print its length.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Files and paths 05: Embed static assets
Check the lesson objective before moving on.
When is an embedded asset read into the program?
Which type exposes an embedded tree through fs.FS?