Examples
A string or []byte takes exactly one file. An embed.FS takes a whole tree and satisfies fs.FS, which is what makes it work with anything that reads a filesystem.
import "embed"
//go:embed version.txt
var version string
//go:embed logo.png
var logo []byte
//go:embed static
var assets embed.FShello from embed
body { color: red }http.FS turns an embed.FS into something the file server understands. fs.Sub strips the directory prefix so URLs do not have to repeat it.
//go:embed static
var assets embed.FS
func main() {
sub, err := fs.Sub(assets, "static")
if err != nil {
log.Fatal(err)
}
http.Handle("/static/", http.StripPrefix("/static/",
http.FileServer(http.FS(sub))))
log.Fatal(http.ListenAndServe(":8080", nil))
}$ curl localhost:8080/static/site.css
body { color: red }Both of these are the everyday use. ParseFS and iofs.New take an fs.FS, so an embedded tree drops straight in with no path handling.
//go:embed templates/*.html
var tmplFS embed.FS
var tmpl = template.Must(
template.ParseFS(tmplFS, "templates/*.html"))
//go:embed migrations/*.sql
var migrations embed.FS
src, err := iofs.New(migrations, "migrations")$ ls
myapp
$ ./myapp
migrations applied, templates parsed, 0 files on diskBy default a directory pattern skips anything starting with a dot or an underscore. The all: prefix includes them.
// Skips static/.hidden and static/_draft.txt
//go:embed static
var assets embed.FS
// Includes them
//go:embed all:static
var everything embed.FS
// Several patterns on one directive, space separated
//go:embed templates/*.html static/css
var mixed embed.FSstatic/site.css
static/greeting.txt| Function | Description |
|---|---|
//go:embed pattern | A directive, not a function. It must sit immediately above a package-level var, with no blank line between. |
The directive is a comment the compiler reads, so its placement is exact. A blank line between it and the | |
type FS struct | A read-only filesystem holding the embedded files. Satisfies fs.FS, fs.ReadDirFS, and fs.ReadFileFS. |
(FS) Open(name string) (fs.File, error) | Opens one embedded file. Paths use forward slashes on every platform. |
(FS) ReadFile(name string) ([]byte, error) assets.ReadFile("static/site.css") | Reads a whole embedded file with no allocation beyond the returned slice. |
(FS) ReadDir(name string) ([]fs.DirEntry, error) | Lists an embedded directory, sorted by filename. |
string //go:embed version.txt
var version string | A var of type string takes the contents of exactly one file. |
[]byte | A var of type []byte also takes exactly one file, unparsed. |
all: prefix | Includes files starting with . or _, which the default patterns skip. |
A pattern naming a directory walks it, and the walk skips entries beginning with | |