Skip to content
Tutorials Center
My learning

Topics

Lesson 91 of 147 ยท Standard Library

Embedding Files with go:embed

Learn how go:embed bundles files and directories into a Go binary - string, []byte and embed.FS variables, patterns, templates, static assets with http.FS, and common mistakes.

One of Go's best features is that a program compiles to a single executable file. That is easy to deploy until your program needs other files: HTML templates, a CSS file, SQL migrations, a default configuration, a font. If those files sit next to the binary, you have to copy them everywhere and hope nobody moves or edits them.

Since Go 1.16 the embed package and the //go:embed directive solve this. The compiler copies the files into the binary, and your code reads them from memory. The result is still one file to ship, and the content cannot go missing at run time.

Your first embedded file

You add //go:embed on the line directly above a package-level variable, followed by a file name (or pattern). The variable's type decides what you get. You must import the embed package; if you only embed into a string or []byte, import it with a blank identifier: import _ "embed".

The runner on this site compiles a single file named main.go, so the examples embed their own source code. In a real project you would embed other files that live next to your Go file.

Go Embedding a file into a string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The path is relative to the directory of the source file that contains the directive. In a real project, //go:embed greeting.txt would embed the file greeting.txt from the same folder.

How the variable's type shapes the result:

Variable type What you get
string the file's text (a single file only)
[]byte the file's bytes (a single file only)
embed.FS a read-only file system holding one or more files and folders

The directive works only on package-level variables, not on local variables inside a function. The data is fixed at compile time, so the variables are effectively read-only; changing the []byte at run time changes only your copy in memory, never the binary.

flowchart LR
    A["Source files<br/>main.go, index.html, style.css"] --> B["go build"]
    B --> C["Single binary<br/>code + embedded files"]
    C --> D["Program reads files<br/>from memory at run time"]

The compiler reads the files once, at build time. Nothing is read from disk when the program runs.

embed.FS: a read-only file system

Use embed.FS when you have several files or a whole folder. It implements the io/fs.FS interface, so every function that accepts an fs.FS works with it: fs.ReadFile, fs.ReadDir, fs.WalkDir, fs.Glob, template.ParseFS, http.FS and more.

Go Reading from an embed.FS

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Paths inside an embed.FS always use forward slashes (templates/index.html), on every operating system, and never start with / or ./. The root of the file system is called ".". The file system is read-only: you can read, list and walk it, but not write.

Patterns and folders

A directive can list several patterns, and the patterns can use the wildcards of path.Match. Here are the common forms (these are read-only snippets because they need real files):

Go
//go:embed templates/*.html
var pages embed.FS

//go:embed static
var static embed.FS

//go:embed config/default.json LICENSE
var assets embed.FS

//go:embed all:web
var web embed.FS

Several rules apply to patterns:

  • Patterns can't contain . or .. path elements and can't be absolute. You can only embed files inside the package's own folder tree (including subfolders). A file that is in a parent folder cannot be embedded.
  • If a pattern names a directory, the whole folder is embedded recursively, except files whose names start with . or _. Those are skipped because they are usually hidden files or editor leftovers.
  • Add the all: prefix (//go:embed all:web) to include those hidden files too.
  • A pattern that matches nothing is a compile error, which is a feature: you find out at build time that a file is missing.
  • You can't embed files from other modules, symbolic links, or files in a folder that contains its own go.mod file.

Serving static assets with http.FS

A very common use is to ship a website's CSS, JavaScript and images inside a Go web server. http.FS wraps an fs.FS so that http.FileServer can serve it. If your files live in a static folder, fs.Sub removes that prefix from the URLs:

Go
//go:embed static
var staticFiles embed.FS

func newHandler() http.Handler {
	sub, err := fs.Sub(staticFiles, "static")
	if err != nil {
		panic(err) // only fails when the directory name is invalid
	}
	mux := http.NewServeMux()
	mux.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.FS(sub))))
	return mux
}

With this setup, /assets/app.css serves static/app.css from the binary. Learn about handlers and muxes in Building HTTP Servers.

The following program does the same thing end to end. To keep it self-contained it starts a test server on a loopback port and requests its own source file:

Go Serving an embedded file over HTTP

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Note that embed.FS files have no modification time, so FileServer can't send Last-Modified headers. Set your own Cache-Control or use file names that contain a hash if you need caching.

Templates, migrations and defaults

Embedded files are perfect for several recurring jobs:

HTML templates. template.ParseFS(templates, "templates/*.html") parses every matching template from the embedded file system (see Text and HTML Templates). Your web app no longer fails because the working directory differs from where you started it.

SQL migrations. Embed a migrations folder and walk it in order with fs.WalkDir, running each file against the database. The migration tool and the SQL travel together in one executable.

Default configuration. Embed a default-config.json into a []byte, decode it with encoding/json (see JSON), and then override values from a user's file or environment.

Version information. A small VERSION file embedded into a string avoids hard-coding the version in source:

Go
//go:embed VERSION
var version string

func Version() string {
	return strings.TrimSpace(version)
}

Trimming is important, because most editors add a trailing newline to the file and embed keeps the bytes exactly as they are.

Walking an embedded tree

fs.WalkDir visits every file in an fs.FS, in lexical order, which makes the output deterministic:

Go Walking an embed.FS

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

With a real folder you would see each subfolder and file listed, with the root . first.

Common mistakes

  • Forgetting the import. //go:embed needs the embed package imported, even if only as _ "embed".
  • A blank line between the directive and the variable. The directive must be directly above the var line (comments are allowed in between).
  • Embedding at the wrong level. var x string inside main doesn't work; the variable must be at package level.
  • Expecting live reloads. Edited files change only after you rebuild. During development, serve from disk, for example by choosing os.DirFS("static") instead of the embedded file system when an environment variable is set. Both implement fs.FS, so the rest of your code doesn't change.
  • Large files. Everything you embed makes the binary bigger and is loaded with it. Keep huge video or data files outside.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where must the //go:embed directive be placed?

    The directive applies to the package-level variable declared on the line(s) right after it.
  2. 2. Which variable types can go:embed fill?

    string and []byte hold one file; embed.FS holds one or more files and directories.
  3. 3. What happens with //go:embed static if the folder contains a file named .secret?

    Files starting with . or _ are excluded when a directory is embedded. Write //go:embed all:static to include them.
  4. 4. Can you embed ../config.json from a package in a subfolder?

    Embedded files must live in the package directory or below it. Move the file or put the embed directive in a package higher up.
  5. 5. How can you serve an embed.FS over HTTP?

    http.FS adapts any fs.FS to the http.FileSystem interface that http.FileServer expects.

Summary

  • //go:embed copies files into the binary at compile time; place it directly above a package-level variable and import the embed package.
  • Use string or []byte for one file, and embed.FS for several files or folders.
  • embed.FS is a read-only fs.FS, so it works with fs.ReadFile, fs.WalkDir, fs.Sub, template.ParseFS and http.FS.
  • Directory patterns skip names starting with . or _ unless you add all:; patterns can't leave the package's folder, and a pattern with no match is a build error.
  • Typical uses are templates, static assets, SQL migrations, default configuration and version files.
  • Changes to embedded files need a rebuild; use os.DirFS during development if you want live edits.

Next: archive/zip, tar and compress/gzip shows how to create and read archives and compressed streams.