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-onlyfs.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
-
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.FSFile paths are relative to the
.gofile containing the directive. -
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.Subrebases the FS at a subdirectory soassets/app.cssbecomes/static/app.css. -
Serve with ETag and cache headers. stdlib
http.FileServerdoes 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. -
Load HTML templates from embed.
import ( "html/template" ) tpl := template.Must(template.ParseFS(templatesFS, "templates/*.html")) tpl.ExecuteTemplate(w, "index.html", data)ParseFSreads through the embed FS exactly likeParseFilesreads from disk. -
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 } -
Dev vs prod via build tags. A
devbuild 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.FSThen
go run -tags dev ./cmd/apireads from disk (saves trigger a re-run via Air), andgo build ./cmd/apiproduces a binary with embedded assets. -
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 -wstrips 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 dirskips.git,.DS_Store, etc. Add//go:embed all:dirto include them — usually you don’t want that. - Globs do not recurse.
//go:embed templates/*.htmlmatches only the top level. Use//go:embed templatesto grab the whole subtree. fs.Subreturns anfs.FS, notembed.FS. Code that types asembed.FSdoes not accept the result — type your parameters asfs.FS.embed.FSpaths use forward slashes on Windows too. Stdlibpath/filepathuses OS separators;pathuses/. 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:embedto 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.