Skip to content

Embedding static assets in Go binaries with embed.FS

Ship your Go web app as one binary by using the embed package built into Go to compile its templates, SQL migrations and static files into the executable. You will also serve those files with long-lived cache headers and keep a development mode that reads them straight from disk.

If you build web apps in Go, you can ship each one as a single binary with its templates, CSS and SQL migrations baked inside. Without that, those files travel as separate folders next to the binary. The folder layout on the server then has to match your repository exactly, and a missing file only shows up as an error once the app is running. Go 1.16 added the //go:embed directive, a special comment that tells the compiler to copy files into the binary at build time. Your code reads them back through embed.FS, a read-only file system that works with http.FileServer, html/template and migration tools. The sections below cover serving static files, loading templates, running migrations, a disk-based mode for development and what embedding does to binary size.

How to verify

After embedding, a single binary is the only artifact you need:

go build -o ./bin/api ./cmd/api
ls -lh ./bin/api
./bin/api migrate up
./bin/api &
curl http://localhost:8080/static/app.css
curl -sI http://localhost:8080/static/app.css | grep -i etag

If the binary contains the migrations and the static asset is served with an ETag header, embedding is wired correctly. Run strings ./bin/api | grep app.css and you should see the file name in the binary’s symbol table.

What’s happening

The embed package gives you three ways to bundle files at compile time:

  • //go:embed file.txt + var s string — for a single text file.
  • //go:embed file.bin + var b []byte — for a single binary blob.
  • //go:embed dir/* assets/templates/*.html migrations + var fs embed.FS — for a directory tree, exposed as a read-only fs.FS.

embed.FS implements fs.FS, fs.ReadFileFS, and fs.ReadDirFS. Anything that takes an fs.FS (which is most of the modern stdlib — html/template.ParseFS, database/sql migrate libraries, http.FS`) accepts an embedded FS.

The catch: changes to embedded files require a rebuild. For dev productivity, you serve from the real filesystem in development and from embed.FS in production — selected at build time with build tags or at runtime via a flag.

The procedure

  1. Embed a directory tree.

    package main
    
    import (
        "embed"
        "io/fs"
        "net/http"
    )
    
    //go:embed assets
    var assetsFS embed.FS
    
    //go:embed migrations
    var migrationsFS embed.FS
    
    //go:embed templates/*.html
    var templatesFS embed.FS

    File paths are relative to the .go file containing the directive.

  2. Serve embedded static files via http. assets/ becomes /static/:

    sub, _ := fs.Sub(assetsFS, "assets")
    mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(sub))))

    fs.Sub rebases the FS at a subdirectory so assets/app.css becomes /static/app.css.

  3. Serve with ETag and cache headers. stdlib http.FileServer does not set ETag — wrap it:

    func cacheControl(h http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
            h.ServeHTTP(w, r)
        })
    }
    
    mux.Handle("/static/", cacheControl(http.StripPrefix("/static/", http.FileServer(http.FS(sub)))))

    For ETag, use the content-hashed asset name pattern (/static/app.abc123.css) so the URL itself is the cache key.

  4. Load HTML templates from embed.

    import (
        "html/template"
    )
    
    tpl := template.Must(template.ParseFS(templatesFS, "templates/*.html"))
    tpl.ExecuteTemplate(w, "index.html", data)

    ParseFS reads through the embed FS exactly like ParseFiles reads from disk.

  5. Run SQL migrations from embed. With golang-migrate:

    import (
        "github.com/golang-migrate/migrate/v4"
        _ "github.com/golang-migrate/migrate/v4/database/postgres"
        "github.com/golang-migrate/migrate/v4/source/iofs"
    )
    
    src, err := iofs.New(migrationsFS, "migrations")
    if err != nil { return err }
    m, err := migrate.NewWithSourceInstance("iofs", src, "postgres://...")
    if err != nil { return err }
    if err := m.Up(); err != nil && err != migrate.ErrNoChange { return err }
  6. Dev vs prod via build tags. A dev build that reads from disk:

    //go:build dev
    
    package main
    
    import (
        "io/fs"
        "os"
    )
    
    var assetsFS = os.DirFS("./assets")
    //go:build !dev
    
    package main
    
    import "embed"
    
    //go:embed assets
    var assetsFS embed.FS

    Then go run -tags dev ./cmd/api reads from disk (saves trigger a re-run via Air), and go build ./cmd/api produces a binary with embedded assets.

  7. Verify the embedded payload size. Embedded files grow the binary:

    go build -o bin/api ./cmd/api
    du -sh bin/api
    GOOS=linux go build -ldflags="-s -w" -o bin/api-linux ./cmd/api
    du -sh bin/api-linux

    -s -w strips DWARF and shaves ~30% off the binary. A 20 MB binary with 5 MB of embedded assets is normal.

Common pitfalls

  • Hidden files are excluded by default. //go:embed dir skips .git, .DS_Store, etc. Add //go:embed all:dir to include them — usually you don’t want that.
  • Globs do not recurse. //go:embed templates/*.html matches only the top level. Use //go:embed templates to grab the whole subtree.
  • fs.Sub returns an fs.FS, not embed.FS. Code that types as embed.FS does not accept the result — type your parameters as fs.FS.
  • embed.FS paths use forward slashes on Windows too. Stdlib path/filepath uses OS separators; path uses /. Mismatching them is a portability bug.
  • A binary that grew by 100 MB when you added “just a few assets” is hiding a huge file. Run go tool nm bin/api | grep go:embed to enumerate what is embedded and how big.

Stack Harbor builds single-binary Go services with embedded assets, templates, and migrations on every operations engagement we run — the deploy is kubectl set image or systemctl restart, not an asset sync. See how that fits into our managed operations practice.