Embed Static Assets and Version Info With embed and ldflags
Bundle templates or static files into the binary with //go:embed and inject release versions with -ldflags "-X ...". After this, your binary carries its own assets and build metadata.
Course content
Sign in to save your progress.
-
Bounded Concurrency and Worker Pools
-
Bound Concurrency With a Worker Pool
-
Coordinate Shared State With sync.Mutex and atomic
-
-
-
Memory, Allocations, and Benchmarking
-
Measure Speed and Allocations With go test -bench
-
Cut Allocations With Pre-Sizing and sync.Pool
-
-
-
Profiling and Diagnostics
-
Find CPU and Heap Hotspots With pprof
-
Catch Goroutine Leaks and Slow Tests Early
-
-
-
Resilience and Defensive HTTP
-
Add Retries With Backoff and Jitter
-
Protect Endpoints With Rate Limiting and Panic Recovery
-
-
-
Production Builds and Containers
-
Embed Static Assets and Version Info With embed and ldflags
-
Ship a Multi-Stage Scratch Go Container
-
-
-
Fuzzing, GC Tuning, Tracing, and Reflection
-
Fuzz Testing Parsers and Decoders With go test -fuzz
-
Escape Analysis and GC Tuning (-gcflags="-m", GOGC, GOMEMLIMIT)
-
Execution Tracing and Block/Mutex Contention Profiling
-
Reflection, Struct Tags, and go generate
-
-
Shipping a compiled Go binary alongside a loose folder of HTML templates, SQL migrations, or static assets breaks the "single binary" promise the moment someone runs your binary from another working directory (open templates/index.html: no such file or directory). Meanwhile, binaries deployed without embedded release metadata leave on-call engineers guessing which Git commit is actually running in staging or production.
Go solves both inside the standard toolchain: //go:embed compiles files and entire folders straight into your executable, while -ldflags="-X ..." and runtime/debug.ReadBuildInfo() stamp version and VCS commit metadata directly at build time.
Skip ahead
If you already embed files with //go:embed and embed.FS, strip sub-paths with fs.Sub, and inject release tags with -ldflags="-X ...", continue to "Ship a Multi-Stage Scratch Go Container."
Experiment 1: Embedding a file and stamping version info at link time
Notice two small rules in this program: importing _ "embed" is mandatory whenever you embed into a string or []byte (you only omit the underscore when declaring an embed.FS), and -ldflags="-X ..." only works on package-level var strings—never const:
package main
import (
_ "embed"
"fmt"
"runtime/debug"
)
//go:embed version_note.txt
var note string
var version = "dev"
func main() {
commit := "unknown"
if info, ok := debug.ReadBuildInfo(); ok {
for _, s := range info.Settings {
if s.Key == "vcs.revision" {
commit = s.Value
}
}
}
fmt.Printf("version=%s commit=%s note=%q\n", version, commit, note)
}
$ go build -ldflags="-s -w -X main.version=v1.4.2" -o app .
$ ./app
version=v1.4.2 commit=unknown note="embedded ok"
When built inside a Git working tree (without disabling VCS stamping), Go automatically populates vcs.revision and vcs.modified inside debug.ReadBuildInfo() even without passing -X! Passing -X main.version=v1.4.2 adds your human release tag cleanly on top.
Experiment 2: Embedding a whole directory with embed.FS and fs.Sub
When you have dozens of SQL migration files or static CSS/JS assets, embed the directory into an embed.FS. Use fs.Sub when you want URLs like /app.css to map cleanly without an extra static/ prefix:
//go:embed static/*
var rawAssets embed.FS
func newAssetHandler() (http.Handler, error) {
sub, err := fs.Sub(rawAssets, "static")
if err != nil {
return nil, err
}
return http.FileServerFS(sub), nil
}
Because embed.FS is read-only and baked directly into the binary's data segment at compile time, concurrent HTTP handlers read from it safely with zero locks, zero disk I/O, and zero missing-file bugs in containers.
Experiment 3: Dotfiles and all:
By default, //go:embed static/* skips hidden dotfiles (like .well-known/security.txt) and files beginning with _. If your static site or templates need hidden files included, add the all: prefix: //go:embed all:static.
Experiment 4: Injecting into an internal package with -X
In real repositories where version info lives inside internal/buildinfo/version.go (instead of package main), pass the full module import path to -X:
$ go build -ldflags="-s -w -X example.com/ordersvc/internal/buildinfo.Version=v2.1.0" ./cmd/api
You can verify the exact symbol name inside a compiled binary anytime with go tool nm ./app | grep Version.
Common mistakes
- Declaring
const version = "dev"instead ofvar version = "dev": Constants are inlined at compile time, so-Xsilently fails to overwrite them. Always usevar. - Embedding secrets or
.envfiles with//go:embed: Embedded bytes sit in plain sight inside the compiled executable and can be extracted withstrings ./app. Pass secrets via environment variables or mounted secret files at runtime. - Using relative parent paths like
//go:embed ../migrations: Go forbids..in embed patterns for security and module integrity—place theembed.gofile in the parent directory abovemigrations/and export theembed.FSvariable instead.
💡 Tip
Add a -version flag (or log version + vcs.revision on startup via slog.Info) so every container log stream immediately proves which build is running.
What happens if you skip this step
Containerized Go apps crash with no such file or directory whenever a Dockerfile forgets to copy a template folder, and incident responders waste critical minutes trying to figure out whether a hotfix actually rolled out.
You define const version = "dev" and build with go build -ldflags="-X main.version=v1.5.0", yet ./app still prints dev. Why did -X have no effect?
About
Bundle templates or static files into the binary with //go:embed and inject release versions with -ldflags "-X ...". After this, your binary carries its own assets and build metadata.
- Duration
- 5 min
- Last update
- 11/27/2026
Comments
Sign in to commentNo comments yet.