Embed Files With go:embed

Bundle text and template directories into the binary with go:embed directives, then read them through io/fs without shipping loose files.

GoConfig Management

Code

gosnippet
33 lines
package main

import (
	"embed"
	"fmt"
	"io/fs"
)

// 编译期要求 banner.txt 与源文件同目录,缺失直接构建失败
//go:embed banner.txt
var banner string

// 目录整体嵌入:路径前缀保留,读法与普通文件系统一致
//go:embed templates
var templates embed.FS

func main() {
	fmt.Print(banner)

	entries, err := fs.ReadDir(templates, "templates")
	if err != nil {
		panic(err)
	}
	for _, entry := range entries {
		fmt.Println("template:", entry.Name())
	}

	data, err := fs.ReadFile(templates, "templates/base.html")
	if err != nil {
		panic(err)
	}
	fmt.Printf("base.html is %d bytes\n", len(data))
}

Two embed targets

One //go:embed banner.txt directive binds a string, and a second directive binds the whole templates directory as an embed.FS. The directives sit directly above their variables, so the mapping is visible in one place.

Build-time check

The compiler enforces that banner.txt exists next to the source file; a missing file or directory fails the build before any binary is produced.

Reading through io/fs

The code walks the embedded FS with fs.ReadDir(templates, “templates”) and prints each entry name behind a template: label, then reads templates/base.html with fs.ReadFile and prints its byte length via a base.html is N bytes line. Paths keep the embedded prefix, so the FS behaves like a normal filesystem rooted at templates.

Interactive Tools for This Topic

FAQ

What happens if an embedded file is missing?
The build fails at compile time because //go:embed resolves its paths while compiling, before any binary exists.
Why use embed.FS instead of a map of strings?
embed.FS keeps directory structure and works with the io/fs APIs (ReadDir, ReadFile), so the same code paths serve embedded and real filesystems.