These are the notes for Go episode 73. A customer complains that their bill is wrong. Raju fixed exactly that bug last week, but is the fix running in production? Nobody knows which build is on that server. A medicine strip has a batch number printed on it when it's made; our binary needs the same. From there we invent the whole path from source code to a release: a version stamped in at build time, the right code for each operating system, a static, trimmed, reproducible binary, a 7.87 MB container image, automated releases, and a CI robot that checks every change.
All Go outputs below are from real runs (Go 1.24.7, linux/amd64), through the same runner the video's compiler uses (error streams are printed after normal output). The Docker runs are real too (Docker Engine 29.9.3, 14 November 2026). One honest detail: this sandbox can't download images from Docker Hub or gcr.io, so the build stage's golang:1.24.7 image was made locally (with docker import) from the same Go 1.24.7 toolchain plus a shell. Its size is not the size of the official golang image, so these notes never quote it as such; the scratch final images and every command's output are exactly what Docker printed.
Facts and sources
- Go 1.22 release notes (go.dev/doc/go1.22, "Linker"): "The -w flag suppresses DWARF debug information generation. The -s flag suppresses symbol table generation. The -s flag also implies the -w flag, which can be negated with -w=0."
- distroless README (GitHub, GoogleContainerTools/distroless, read for this episode): "Distroless images contain only your application and its runtime dependencies. They do not contain package managers, shells or any other programs you would expect to find in a standard Linux distribution." "The smallest distroless image, gcr.io/distroless/static-debian13, is around 2 MiB. That's about 50% of the size of alpine (~5 MiB), and less than 2% of the size of debian (124 MiB)." Tags:
latest,nonroot,debug,debug-nonroot. - GoReleaser docs (its GitHub repository,
www/content): "GoReleaser is a release automation tool." "Instead of writing scripts, you write a simple YAML configuration file", and "run a single command to build, archive, package, sign, and publish artifacts." The quick start usesgoreleaser init,goreleaser release --snapshot --clean,git tag -a v0.1.0 -m "First release", aGITHUB_TOKENenvironment variable, andgoreleaser release --clean. Archiveformats:is the plural form added in v2.6. - govulncheck (golang/vuln README): tooling "backed by the Go vulnerability database, which is curated by the Go security team"; it reduces noise "by only surfacing vulnerabilities in functions that your code is actually calling"; install with
go install golang.org/x/vuln/cmd/govulncheck@latest, rungovulncheck ./.... - staticcheck (dominikh/go-tools README): "Using static analysis, it finds bugs and performance issues, offers simplifications, and enforces style rules."
- GitHub Actions: the READMEs of actions/checkout and actions/setup-go (read for this episode) use
actions/checkout@v7andactions/setup-go@v7, and setup-go acceptsgo-version-file: 'go.mod'. go tool dist listwith Go 1.24.7 prints 48 GOOS/GOARCH pairs (13 of them for Linux).
The problem: which version is running?
main.go:
package main
import (
"flag"
"fmt"
)
var version = "dev" // replaced at build time by -ldflags -X
func main() {
showVersion := flag.Bool("version", false, "print the version and exit")
flag.Parse()
if *showVersion {
fmt.Println("shop", version)
return
}
fmt.Println("serving orders...")
}
Run it (from the folder with these files; go.mod says module shop, go 1.24):
go build -o app .
./app -version
go build -ldflags=-X=main.version=1.4.2 -o app .
./app -version
Output:
$ go build -o app .
$ ./app -version
shop dev
$ go build -ldflags=-X=main.version=1.4.2 -o app .
$ ./app -version
shop 1.4.2
go build -o app .compiles the package in the current folder (.) and writes the executable asapp(-o= output name).- The first build says
shop dev: useless when you're trying to find out what's in production. -ldflagspasses flags to the linker, the last step of a build, which joins the compiled packages into one executable.-X main.version=1.4.2sets the package-level string variableversionin packagemainto1.4.2at link time. The code didn't change.
-ldflags -X, the details
# several values at once (a shell keeps the quoted value together)
go build -ldflags="-X main.version=1.4.2 -X main.commit=$(git rev-parse --short HEAD) -X main.date=$(date -u +%Y-%m-%dT%H:%M:%SZ)" .
-Xworks only on a package-levelstringvariable (not aconst, not anint, not a variable initialised by a function call), named by its full import path:main.version, orgithub.com/you/shop/internal/build.Versionfor a non-main package.- In CI, the version usually comes from the git tag (a named pointer to one commit, like
v1.4.2). - A typo is silently ignored:
main.go:
package main
import "fmt"
var version = "dev"
func main() { fmt.Println("shop", version) }
Run it (from the folder with these files; go.mod says module shop, go 1.24):
go build -ldflags=-X=main.Version=1.4.2 -o app .
./app
go version -m app
Output:
$ go build -ldflags=-X=main.Version=1.4.2 -o app .
$ ./app
shop dev
$ go version -m app
app: go1.24.7
path shop
mod shop (devel)
build -buildmode=exe
build -compiler=gc
build -ldflags=-X=main.Version=1.4.2
build CGO_ENABLED=1
build CGO_CFLAGS=
build CGO_CPPFLAGS=
build CGO_CXXFLAGS=
build CGO_LDFLAGS=
build GOARCH=amd64
build GOOS=linux
build GOAMD64=v1
-X main.Version (capital V) names a variable that doesn't exist, so the linker does nothing and says nothing. Notice that go version -m still records the flag you passed. Guard against this in CI by running ./app -version and checking the result.
(The video's compiler panel splits command lines on spaces, which is why its commands write -ldflags=-X=main.version=1.4.2 with = and no spaces; in a real shell, quote the value as above.)
Build info and smaller binaries
The go command records facts about every build inside the binary. runtime/debug.ReadBuildInfo reads them from inside the program; go version -m <binary> prints them from outside.
The episode's program (INFO)
main.go:
package main
import (
"fmt"
"runtime/debug"
)
func main() {
bi, ok := debug.ReadBuildInfo() // what the go command recorded in the binary
if !ok {
return
}
fmt.Println("go:", bi.GoVersion, " module:", bi.Main.Path)
for _, s := range bi.Settings {
fmt.Printf(" %s=%s\n", s.Key, s.Value)
}
}
sizes/main.go:
package main // a tiny helper: prints file sizes
import (
"fmt"
"os"
)
func main() {
for _, name := range os.Args[1:] {
st, err := os.Stat(name)
if err != nil {
fmt.Println(err)
continue
}
fmt.Printf("%-6s %5.2f MB\n", name, float64(st.Size())/1e6)
}
}
Run it (from the folder with these files; go.mod says module shop, go 1.24):
go build -o full .
go build -trimpath -ldflags=-s -o small .
go run ./sizes full small
./small
Output:
$ go build -o full .
$ go build -trimpath -ldflags=-s -o small .
$ go run ./sizes full small
full 2.29 MB
small 1.48 MB
$ ./small
go: go1.24.7 module: shop
-buildmode=exe
-compiler=gc
-trimpath=true
CGO_ENABLED=1
GOARCH=amd64
GOOS=linux
GOAMD64=v1
- Size: 2.29 MB → 1.48 MB.
-sdrops the symbol table (the list of function and variable names that debuggers and profilers use), and since Go 1.22-salso implies-w, which drops DWARF debug information (the data that lets a debugger map machine code back to source lines and variables). The program runs exactly the same; only debugging the binary gets harder. Panic stack traces still show function names and line numbers, because Go keeps its own runtime tables for those. - Build settings recorded: the Go version, the module path,
-trimpath=true,CGO_ENABLED,GOOS,GOARCH,GOAMD64. When you build inside a git checkout, Go also recordsvcs=git,vcs.revision(the commit) ,vcs.timeandvcs.modified(were there uncommitted changes?), so a binary can tell you its commit without any-X. -ldflags=-sis not listed here: when-trimpathis used, Go leaves-ldflagsout of the build info, because linker flags can contain local paths. Without-trimpathit is recorded, as the typo example shows.
Build constraints and cross-compiling
A restaurant chain serves filter coffee in Chennai and masala chai in Delhi; some items are only on the members' menu; and a central kitchen in Mumbai cooks for Pune. Go programs need the same three things: code per operating system, optional editions, and building for another machine.
The obvious way fails (CLASH)
main.go:
package main
import "fmt"
func main() { fmt.Println("sound:", beep()) }
beep_unix.go:
package main
func beep() string { return "linux terminal bell" }
beep_win.go:
package main
func beep() string { return "windows MessageBeep" }
Run it (from the folder with these files; go.mod says module shop, go 1.24):
go build .
Output:
$ go build .
# shop
./beep_win.go:3:6: beep redeclared in this block
./beep_unix.go:3:6: other declaration of beep
Go compiles every .go file in a package's folder, so two files defining beep clash.
Build constraints and file name suffixes (TAGS)
main.go:
package main
import "fmt"
func main() {
fmt.Println("plan:", plan, "| sound:", beep())
}
free.go:
//go:build !pro
package main
const plan = "free"
pro.go:
//go:build pro
package main
const plan = "pro: reports + exports"
beep_linux.go:
package main // the _linux suffix: only built when GOOS=linux
func beep() string { return "linux terminal bell" }
beep_windows.go:
package main // the _windows suffix: only built when GOOS=windows
func beep() string { return "windows MessageBeep" }
Run it (from the folder with these files; go.mod says module shop, go 1.24):
go run .
go run -tags pro .
go list -f={{.GoFiles}} .
GOOS=windows go list -f={{.GoFiles}} .
GOOS=windows GOARCH=arm64 go build -o shop.exe .
Output:
$ go run .
plan: free | sound: linux terminal bell
$ go run -tags pro .
plan: pro: reports + exports | sound: linux terminal bell
$ go list -f={{.GoFiles}} .
[beep_linux.go free.go main.go]
$ GOOS=windows go list -f={{.GoFiles}} .
[beep_windows.go free.go main.go]
$ GOOS=windows GOARCH=arm64 go build -o shop.exe .
- File name suffixes:
_linux.go,_windows.go,_darwin_arm64.goare only compiled whenGOOS(andGOARCH) match._test.gofiles are only compiled bygo test. - A build constraint is a
//go:buildline before thepackageclause, followed by a blank line. It's a boolean expression:&&(and),||(or),!(not), parentheses, and words: a GOOS (linux), a GOARCH (arm64),cgo, a Go version (go1.22, meaning "Go 1.22 or later"),unix, or your own build tags passed withgo build -tags pro. go list -f={{.GoFiles}} .prints which files the build would use;GOOS=windows go list ...asks the same question for Windows.- Cross-compiling = building for an operating system or processor other than the one you're on. Set
GOOSandGOARCH:GOOS=windows GOARCH=arm64 go build -o shop.exe .made a Windows-on-ARM binary on Linux with no extra tools (as long as cgo isn't needed).go tool dist listprints all 48 supported pairs.
//go:build linux && (amd64 || arm64)
package main
Old code may still have // +build lines: that's the syntax from before Go 1.17; gofmt adds the //go:build form and the old one can be deleted once you support only Go 1.17+.
Static binaries with CGO_ENABLED=0
cgo is Go's bridge to C code (episode 75 goes deep). Some standard packages, like net (for looking up host names) and os/user, can use the system's C library (libc) when cgo is enabled. Then the binary is dynamically linked: at start-up, the operating system's loader (ld-linux-x86-64.so.2) must find and attach libc.so.6 on that machine.
The episode's program (STATIC)
main.go:
package main
import (
"fmt"
"net"
)
func main() {
addrs, err := net.LookupHost("localhost") // net can use the C library's resolver
fmt.Println(addrs, err)
}
linkcheck/main.go:
package main // a tiny helper: does a binary need the C library to start?
import (
"debug/elf"
"fmt"
"os"
)
func main() {
for _, name := range os.Args[1:] {
f, err := elf.Open(name)
if err != nil {
fmt.Println(err)
continue
}
libs, _ := f.ImportedLibraries()
if interp := f.Section(".interp"); interp != nil {
b, _ := interp.Data()
fmt.Printf("%-6s dynamic: needs %s %v\n", name, string(b[:len(b)-1]), libs)
} else {
fmt.Printf("%-6s static: needs nothing else %v\n", name, libs)
}
f.Close()
}
}
Run it (from the folder with these files; go.mod says module shop, go 1.24):
go build -o dyn .
CGO_ENABLED=0 go build -o static .
go run ./linkcheck dyn static
Output:
$ go build -o dyn .
$ CGO_ENABLED=0 go build -o static .
$ go run ./linkcheck dyn static
dyn dynamic: needs /lib64/ld-linux-x86-64.so.2 [libc.so.6]
static static: needs nothing else []
.interpis the ELF section that names the loader; a static binary has none. ELF is the file format of Linux executables, anddebug/elfreads it.- With
CGO_ENABLED=0, Go uses its pure-Go implementations (for example its own DNS resolver), and the result is a static binary: one file that runs on any Linux machine with the same architecture, even an empty container. - A static binary can't call C libraries. If you need one (SQLite via
mattn/go-sqlite3, episode 67), you need cgo, a C compiler at build time, and a base image with libc at run time (for examplegcr.io/distroless/base-debian13orcc-debian13).
-trimpath and reproducible builds
Raju builds in /home/raju/shop, and that folder name is recorded in the binary (for panic traces and debuggers).
The episode's program (REPRO)
main.go:
package main
func main() { panic("order failed") } // a panic trace prints source file paths
inspect/main.go:
package main // a tiny helper: build paths inside a binary, and its checksum
import (
"bytes"
"crypto/sha256"
"fmt"
"os"
)
func main() {
dir, _ := os.Getwd() // the folder we built in, e.g. /home/raju/shop
for _, name := range os.Args[1:] {
b, _ := os.ReadFile(name)
n := bytes.Count(b, []byte(dir))
sum := sha256.Sum256(b)
fmt.Printf("%s: build folder found %d time(s), sha256 %x...\n", name, n, sum[:8])
}
}
Run it (from the folder with these files; go.mod says module shop, go 1.24):
go build -o a .
go build -trimpath -o b .
go build -trimpath -o c .
go run ./inspect a b c
Output:
$ go build -o a .
$ go build -trimpath -o b .
$ go build -trimpath -o c .
$ go run ./inspect a b c
a: build folder found 1 time(s), sha256 809a2d5a9ada85da...
b: build folder found 0 time(s), sha256 a74d6c4525f6b39a...
c: build folder found 0 time(s), sha256 a74d6c4525f6b39a...
- SHA-256 is a cryptographic hash: a 32-byte fingerprint of a file's bytes; change one byte and the fingerprint changes completely. We print the first 8 bytes.
a(no-trimpath) contains the build folder; its hash would differ on Priya's laptop, in a different folder. (The video's run builds in a fresh temporary folder each time, soa's hash there differs from this one.)bandc(with-trimpath) contain no local path, and their hashes are identical.- A reproducible build: the same source, the same Go version and the same flags produce byte-for-byte the same binary, on any machine, in any folder. Anyone can rebuild a release and check that it really came from that source. Go's toolchain is designed for this;
-trimpathremoves the main thing that varies (local paths). Embedded build times (-X main.date=...) or VCS state also change the bytes, so take them from the commit (its timestamp), not from the clock, when you need reproducibility.
Docker multi-stage builds
A container is a running program isolated with its own file system and limits; a container image is the packed file system it starts from, built from a recipe called a Dockerfile. Docker can run the same image the same way on any server. A base image is the image a Dockerfile starts FROM. An image layer is the set of file changes one step adds; Docker caches layers, so unchanged steps are reused.
Sending the whole kitchen with every box of sweets is a single-stage build: the toolchain, the source and the binary all ship together. A multi-stage build cooks in stage 1 and sends only the sealed box in stage 2.
The single-stage Dockerfile (for comparison)
FROM golang:1.24.7
WORKDIR /src
COPY . .
RUN go build -o /shop .
ENTRYPOINT ["/shop"]
The episode's Dockerfile
# stage 1: build with the full Go toolchain
FROM golang:1.24.7 AS build
WORKDIR /src
COPY go.mod ./
RUN go mod download
COPY . .
ARG VERSION=dev
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -X main.version=${VERSION}" -o /out/shop .
# stage 2: only the binary, on an empty image
FROM scratch
COPY --from=build /out/shop /shop
USER 65532:65532
EXPOSE 8080
ENTRYPOINT ["/shop"]
The program inside, main.go:
package main
import (
"fmt"
"log"
"net/http"
)
var version = "dev"
func main() {
http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "ok, version", version)
})
log.Println("shop", version, "listening on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
FROM golang:1.24.7 AS buildnames stage 1build.COPY go.mod ./thenRUN go mod downloadbeforeCOPY . .: dependencies change less often than code, so Docker can reuse the cached download layer (with dependencies you'd also copygo.sum).ARG VERSION=devis a build argument, set withdocker build --build-arg VERSION=1.4.2.CGO_ENABLED=0gives a static binary, whichscratchneeds.-trimpathand-sas above.FROM scratchstarts stage 2 from Docker's completely empty image.COPY --from=buildtakes only the binary.USER 65532:65532runs as an unprivileged user and group (65532 is the user id distroless uses for its nonroot images), not as root, the all-powerful administrator account.EXPOSE 8080documents the port;ENTRYPOINT ["/shop"]is the command the container runs.
docker build and docker images (real)
$ docker build --build-arg VERSION=1.4.2 -t shop:1.4.2 .
(build log trimmed)
#8 [build 4/6] RUN go mod download
#8 0.184 go: no module dependencies to download
#10 [build 6/6] RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -X main.version=1.4.2" -o /out/shop .
#10 DONE 30.5s
#11 [stage-1 1/1] COPY --from=build /out/shop /shop
#11 DONE 0.0s
#12 naming to docker.io/library/shop:1.4.2 done
$ docker images shop
IMAGE ID DISK USAGE CONTENT SIZE
shop:1.4.2 2d926b17e1de 7.87MB 2.36MB
shop:single 848a805d212a 518MB 110MB
The multi-stage image is 7.87 MB; the single-stage image on this machine's Go image, toolchain and all, is 518 MB, for the same program. ("Content size" is the compressed size of the image's layers.)
Running it (real)
$ docker run -d --name shop -p 18080:8080 shop:1.4.2
52a2ed9d7eca6ee2a859c58ad620b99686ccf97d9d5462c895502397ce4563b1
$ curl localhost:18080/healthz
ok, version 1.4.2
$ docker logs shop
2026/11/14 05:39:07 shop 1.4.2 listening on :8080
$ docker exec shop sh
OCI runtime exec failed: exec failed: unable to start container process: exec: "sh": executable file not found in $PATH
-druns in the background;-p 18080:8080maps port 18080 on the laptop to 8080 inside the container.- There's no shell in the image: nothing but our binary. A smaller attack surface (fewer programs an attacker could use) and fewer packages to patch.
The classic failure: a dynamic binary in scratch (real)
$ cat Dockerfile.dyn
FROM scratch
COPY shop-dyn /shop
ENTRYPOINT ["/shop"]
$ docker run --rm shop:dyn
exec /shop: no such file or directory
shop-dyn was built on the laptop with cgo enabled. The file is there; what's missing is the loader /lib64/ld-linux-x86-64.so.2 it asks for (and libc), and the kernel reports the missing loader as "no such file or directory". Fix: CGO_ENABLED=0, or a base image with libc.
scratch or distroless?
scratch |
gcr.io/distroless/static-debian13 |
|
|---|---|---|
| Contents | nothing | CA certificates, tzdata, a /tmp directory and an /etc/passwd entry for root (no shell, no package manager) |
| Size | 0 + your binary | around 2 MiB + your binary |
| HTTPS calls to other servers | fail with x509 certificate errors unless you copy CA certificates in | work |
time.LoadLocation("Asia/Kolkata") |
fails unless you embed tzdata (import _ "time/tzdata") |
works |
| Debugging | nothing inside | :debug tag adds a busybox shell |
| Non-root | USER 65532:65532 |
:nonroot tag (distroless's nonroot user is 65532) |
CA certificates are the files that let a program check that an HTTPS server's certificate is genuine. x509 is the certificate format, so missing certificates show up as x509 errors. tzdata is the time zone database.
Releasing with GoReleaser
A release is a published version: binaries for each supported system, packed into archives (.tar.gz, .zip), a checksums file (SHA-256 of every archive, so downloads can be verified), and release notes, uploaded somewhere like GitHub Releases. Doing it by hand is like packing parcels for six cities yourself.
version: 2
builds:
- env: [CGO_ENABLED=0]
goos: [linux, windows, darwin]
goarch: [amd64, arm64]
flags: [-trimpath]
ldflags: ["-s -X main.version={{.Version}}"]
archives:
- formats: [tar.gz]
checksum:
name_template: checksums.txt
goreleaser init # writes a starting .goreleaser.yaml
goreleaser release --snapshot --clean # a local test: builds everything, publishes nothing
git tag -a v1.4.2 -m "v1.4.2" && git push --tags
export GITHUB_TOKEN=... # a token allowed to create releases
goreleaser release --clean # build, archive, checksum, publish
- 3 operating systems × 2 architectures = 6 binaries.
darwinis macOS's GOOS. {{.Version}}is a GoReleaser template field: the version from the git tag, without thev.- GoReleaser can also build Docker images, Linux packages and Homebrew formulas, and sign artifacts; see its docs for those.
- (This config was not run in this sandbox; it follows the GoReleaser v2 docs read for the episode.)
CI: checks on every change
CI (continuous integration) = a service that runs your checks automatically on every push and every pull request (a proposed change waiting to be reviewed and merged). If a check fails, the change is marked red and isn't merged. If all are green, the pipeline can build the image and the release (CD, continuous delivery).
| Check | What it finds | Ran in this episode? |
|---|---|---|
go vet ./... |
suspicious code the compiler accepts: wrong Printf verbs, copied locks, unreachable code |
yes |
staticcheck ./... |
more bugs, performance issues, simplifications, style | (in the pipeline only) |
go test -race ./... |
failing tests and data races | yes |
govulncheck ./... |
known vulnerabilities in dependencies, only in functions you actually call | (in the pipeline only; needs vuln.go.dev, not reachable from this sandbox) |
go vet (CI1)
shop.go:
package shop
import (
"fmt"
"sync"
)
func Receipt(id string, paise int) string {
return fmt.Sprintf("order %d: Rs %d", id, paise/100) // %d for a string: a bug
}
type Counter struct{ n int }
func (c *Counter) Add() { c.n++ } // no lock
func Count(orders int) int {
var c Counter
var wg sync.WaitGroup
for range orders {
wg.Add(1)
go func() { defer wg.Done(); c.Add() }() // many goroutines, one counter
}
wg.Wait()
return c.n
}
shop_test.go:
package shop
import "testing"
func TestCount(t *testing.T) {
if got := Count(50); got != 50 {
t.Errorf("Count(50) = %d", got)
}
}
Run it (from the folder with these files; go.mod says module shop, go 1.24):
go vet ./...
Output:
$ go vet ./...
# shop
# [shop]
./shop.go:9:12: fmt.Sprintf format %d has arg id of wrong type string
%d is the verb for integers, but id is a string. It compiles, and at run time would print order %!d(string=A1). go vet catches it before any customer sees a broken receipt. (go test also runs a subset of vet checks, including this one, before every test run.)
go test -race (CI2)
shop.go:
package shop
import (
"fmt"
"sync"
)
func Receipt(id string, paise int) string {
return fmt.Sprintf("order %s: Rs %d", id, paise/100) // fixed after go vet
}
type Counter struct{ n int }
func (c *Counter) Add() { c.n++ } // no lock
func Count(orders int) int {
var c Counter
var wg sync.WaitGroup
for range orders {
wg.Add(1)
go func() { defer wg.Done(); c.Add() }() // many goroutines, one counter
}
wg.Wait()
return c.n
}
shop_test.go:
package shop
import "testing"
func TestCount(t *testing.T) {
if got := Count(50); got != 50 {
t.Errorf("Count(50) = %d", got)
}
}
Run it (from the folder with these files; go.mod says module shop, go 1.24):
go test -race ./...
Output:
$ go test -race ./...
==================
WARNING: DATA RACE
Read at 0x00c000012338 by goroutine 8:
shop.(*Counter).Add()
shop.go:14 +0x84
shop.Count.func1()
shop.go:21 +0x12
Previous write at 0x00c000012338 by goroutine 57:
shop.(*Counter).Add()
shop.go:14 +0x96
shop.Count.func1()
shop.go:21 +0x12
Goroutine 8 (running) created at:
shop.Count()
shop.go:21 +0x87
shop.TestCount()
shop_test.go:6 +0x2e
testing.tRunner()
/usr/local/go1.24.7/src/testing/testing.go:1792 +0x225
testing.(*T).Run.gowrap1()
/usr/local/go1.24.7/src/testing/testing.go:1851 +0x44
Goroutine 57 (finished) created at:
shop.Count()
shop.go:21 +0x87
shop.TestCount()
shop_test.go:6 +0x2e
testing.tRunner()
/usr/local/go1.24.7/src/testing/testing.go:1792 +0x225
testing.(*T).Run.gowrap1()
/usr/local/go1.24.7/src/testing/testing.go:1851 +0x44
==================
==================
WARNING: DATA RACE
Write at 0x00c000012338 by goroutine 15:
shop.(*Counter).Add()
shop.go:14 +0x96
shop.Count.func1()
shop.go:21 +0x12
Previous write at 0x00c000012338 by goroutine 44:
shop.(*Counter).Add()
shop.go:14 +0x96
shop.Count.func1()
shop.go:21 +0x12
Goroutine 15 (running) created at:
shop.Count()
shop.go:21 +0x87
shop.TestCount()
shop_test.go:6 +0x2e
testing.tRunner()
/usr/local/go1.24.7/src/testing/testing.go:1792 +0x225
testing.(*T).Run.gowrap1()
/usr/local/go1.24.7/src/testing/testing.go:1851 +0x44
Goroutine 44 (finished) created at:
shop.Count()
shop.go:21 +0x87
shop.TestCount()
shop_test.go:6 +0x2e
testing.tRunner()
/usr/local/go1.24.7/src/testing/testing.go:1792 +0x225
testing.(*T).Run.gowrap1()
/usr/local/go1.24.7/src/testing/testing.go:1851 +0x44
==================
--- FAIL: TestCount (0.00s)
shop_test.go:7: Count(50) = 49
testing.go:1490: race detected during execution of test
FAIL
FAIL shop 0.013s
FAIL
WARNING: DATA RACE: a read and a previous write to the same memory in Counter.Add, from two goroutines, with no synchronisation (episode 46). Without -race, TestCount often passes by luck.
A GitHub Actions workflow
# .github/workflows/ci.yml
on: [push, pull_request]
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-go@v7
with: { go-version-file: go.mod }
- run: go vet ./...
- run: go run honnef.co/go/tools/cmd/staticcheck@latest ./...
- run: go test -race ./...
- run: go run golang.org/x/vuln/cmd/govulncheck@latest ./...
- run: docker build --build-arg VERSION=${{ github.sha }} .
- GitHub Actions is GitHub's CI service; a workflow is a YAML file in
.github/workflows/; a job runs on a fresh virtual machine (a runner); steps run in order, and any failing step fails the job. go run pkg@versionruns a tool without installing it. Pin versions (instead of@latest) for repeatable pipelines.${{ github.sha }}is the commit being tested.- (This workflow was not run here; it follows the actions' READMEs.)
Build and release in one page
push / pull request
│
CI checks: go vet · staticcheck · go test -race · govulncheck
│ green
go build: CGO_ENABLED=0 -trimpath -ldflags="-s -X main.version=…"
│
docker build: multi-stage → scratch / distroless, USER 65532 (7.87 MB)
│ git tag v1.4.2
goreleaser release: 6 binaries, archives, checksums.txt
Mini project: ship the shop
- Stamp version, commit and build date with
-ldflags -X, and serve them as JSON on/version. - A multi-stage Dockerfile:
CGO_ENABLED=0,-trimpath,scratch, user 65532, build arguments for the stamps. - A pro edition behind
//go:build pro, selected by a build argument. ci.ymlwith vet, staticcheck,-race, govulncheck and the image build.- A
.goreleaser.yamlfor 6 targets, tested with--snapshot.
Solution (parts 1–3, built and run for real)
main.go:
package main
import (
"encoding/json"
"log"
"net/http"
"runtime"
)
// set at build time with -ldflags -X
var (
version = "dev"
commit = "none"
date = "unknown"
)
func main() {
http.HandleFunc("/version", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"version": version, "commit": commit, "date": date,
"edition": edition, "go": runtime.Version(),
})
})
log.Printf("shop %s (%s, %s edition) listening on :8080", version, commit, edition)
log.Fatal(http.ListenAndServe(":8080", nil))
}
edition_free.go and edition_pro.go:
//go:build !pro
package main
const edition = "free"
//go:build pro
package main
const edition = "pro"
Dockerfile:
FROM golang:1.24.7 AS build
WORKDIR /src
COPY go.mod ./
RUN go mod download
COPY . .
ARG VERSION=dev COMMIT=none DATE=unknown TAGS=""
RUN CGO_ENABLED=0 go build -trimpath -tags "${TAGS}" \
-ldflags="-s -X main.version=${VERSION} -X main.commit=${COMMIT} -X main.date=${DATE}" \
-o /out/shop .
FROM scratch
COPY --from=build /out/shop /shop
USER 65532:65532
EXPOSE 8080
ENTRYPOINT ["/shop"]
Real run:
$ docker build -q --build-arg VERSION=1.5.0 --build-arg COMMIT=9f3c1a2 --build-arg DATE=2026-11-14T05:45:00Z --build-arg TAGS=pro -t shop:1.5.0-pro .
sha256:0fdba23bcc88e304e3a0368382d8198da33c3b0a763fb5e5a89fcd2ccc632681
$ docker run -d --name s2 -p 18081:8080 shop:1.5.0-pro
$ curl localhost:18081/version
{"commit":"9f3c1a2","date":"2026-11-14T05:45:00Z","edition":"pro","go":"go1.24.7","version":"1.5.0"}
$ docker logs s2
2026/11/14 05:50:35 shop 1.5.0 (9f3c1a2, pro edition) listening on :8080
$ docker images shop:1.5.0-pro
IMAGE ID DISK USAGE CONTENT SIZE EXTRA
shop:1.5.0-pro 0fdba23bcc88 8.12MB 2.42MB
Parts 4 and 5 are the ci.yml and .goreleaser.yaml shown above; in CI, pass the stamps from git: --build-arg VERSION=${GITHUB_REF_NAME} --build-arg COMMIT=${GITHUB_SHA::7}.
Common mistakes (and the real messages)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
| no version in the binary | shop dev in production |
nothing stamped | -ldflags "-X main.version=..." |
-X main.Version (typo) |
still shop dev, no error |
unknown names are silently ignored | check ./app -version in CI |
-X on a const or an int |
value unchanged | -X sets only string variables |
var version = "dev" |
two beep() files, no suffix |
beep redeclared in this block |
every .go file in the folder is compiled |
_linux.go / //go:build |
a cgo binary in scratch |
exec /shop: no such file or directory |
no loader or libc in the image | CGO_ENABLED=0 |
scratch + HTTPS calls |
x509 certificate errors | no CA certificates | distroless static, or copy CA certs |
| single-stage image | 518 MB image with the toolchain | the kitchen shipped with the box | multi-stage build |
COPY . . before go mod download |
every code change re-downloads modules | cache layer invalidated | copy go.mod/go.sum first |
| running as root in the container | a break-in gets root inside | default user is root | USER 65532:65532 or :nonroot |
wrong Printf verb |
fmt.Sprintf format %d has arg id of wrong type string (vet) |
compiles, prints %!d(string=...) |
go vet in CI |
no -race in CI |
races found by customers | tests pass by luck | go test -race ./... |
Practice
- Add
-X main.commit=...to the VER program and print both. What happens ifcommitis declared asvar commit stringbut never assigned in the code? - Write
open_windows.goandopen_other.go(with//go:build !windows) that each definefunc openBrowser(url string) error. Check withgo listwhich file each GOOS uses. - Build the STATIC program with
CGO_ENABLED=0 GOOS=linux GOARCH=arm64. What does the helper print? Can you run it on your amd64 laptop? - Your service calls
https://api.payments.examplefrom ascratchimage and fails. Give two fixes. - Reorder this Dockerfile for better caching:
COPY . .,RUN go mod download,RUN go build .... - Why do some teams pin
staticcheck@2025.1.1instead of@latestin CI?
Solutions
1. It works the same way: -X main.commit=9f3c1a2 sets it. A var commit string with no initialiser starts as "" and -X can still set it; without -X, it prints an empty string, so give it a default like "none".
2.
// open_windows.go
package main
import "os/exec"
func openBrowser(url string) error { return exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start() }
// open_other.go
//go:build !windows
package main
import "os/exec"
func openBrowser(url string) error { return exec.Command("xdg-open", url).Start() }
go list -f={{.GoFiles}} . lists open_other.go on Linux; GOOS=windows go list -f={{.GoFiles}} . lists open_windows.go. (A real program would also handle macOS's open.)
3. static: needs nothing else []: still static (no .interp). It's an ARM64 binary, so an amd64 machine can't run it directly (exec format error), unless an emulator is set up; that's what cross-compiling is for: build here, run there.
4. (a) Use gcr.io/distroless/static-debian13, which includes CA certificates. (b) Copy them into scratch from the build stage: COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ (the official golang image is Debian-based and has them).
5.
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN go build ...
Now a code change only re-runs the last two steps; the downloaded modules stay cached.
6. Repeatability: @latest can bring a new version with new checks overnight, turning a green build red with no code change. Pin it, and upgrade on purpose.
Quick quiz
1. This image builds, but docker run prints exec /shop: no such file or directory. Why? (From the video.)
FROM golang:1.24.7 AS build
WORKDIR /src
COPY . .
RUN CGO_ENABLED=1 go build -o /out/shop .
FROM scratch
COPY --from=build /out/shop /shop
ENTRYPOINT ["/shop"]
A. /shop was not copied · B. scratch has no shell · C. the binary needs libc · D. port 8080 is busy
Answer
C. With cgo on, the binary is dynamically linked and needs the loader and libc at start-up; scratch has neither. Build with CGO_ENABLED=0, or use a base image with libc.
2. Which flag removes local file system paths from the binary?
Answer
-trimpath.
3. Since Go 1.22, what does -ldflags=-s do on its own?
Answer
It omits the symbol table and (because -s now implies -w) the DWARF debug information. -s -w=0 keeps DWARF.
4. Which file does GOOS=windows go build use: beep_linux.go or beep_windows.go? And a file starting with //go:build pro?
Answer
beep_windows.go. The pro file is used only when you pass -tags pro.
Interview questions
- How do you embed a version in a Go binary? A package-level string variable set with
go build -ldflags "-X main.version=..."; alsodebug.ReadBuildInfofor the module version and VCS commit recorded automatically. - What do
-sand-wdo?-sstrips the symbol table,-wthe DWARF debug info; since Go 1.22,-simplies-w. Smaller binaries, harder debugging. - What are build constraints?
//go:buildboolean expressions (and_GOOS_GOARCH.gofile suffixes) that decide which files a build includes; custom tags come from-tags. - How do you cross-compile? Set
GOOS/GOARCH(GOOS=windows GOARCH=arm64 go build); easy as long as cgo isn't needed. - What does
CGO_ENABLED=0change? No C code; pure-Go replacements for things like the DNS resolver; a statically linked binary that needs no libc. - Why
-trimpath? Removes local paths from binaries (privacy, and identical output across machines), which is key for reproducible builds. - What is a reproducible build, and why care? Same inputs → byte-identical output; anyone can verify that a released binary came from the published source.
- Explain a multi-stage Docker build. Build in a toolchain image, then copy only the artifact into a minimal final image; smaller, fewer vulnerabilities, no build tools in production.
- scratch vs distroless vs alpine? scratch is empty (no certs, tzdata or users); distroless static adds those without a shell or package manager (~2 MiB); alpine is a small full distribution with a shell and package manager (~5 MiB).
- Why run containers as non-root? Limits the damage if the process is compromised.
- What would your Go CI pipeline run?
go vet, staticcheck (or golangci-lint),go test -race(with coverage),govulncheck, then build and publish the image and the release. - What does govulncheck do differently from a plain dependency scanner? It uses the Go vulnerability database and call analysis, so it reports only vulnerabilities in functions your code actually calls.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Build | turning source code into an executable | go build -o app . |
| Executable / binary | a file the machine can run | app, shop.exe |
-o |
the output file name for go build |
-o app |
| Release | a published version with its files | v1.4.2 on GitHub Releases |
| Version | a name for one release | 1.4.2 |
| Semantic versioning | MAJOR.MINOR.PATCH | 1.4.2 → 1.5.0 |
| Git tag | a named pointer to one commit | v1.4.2 |
| Commit hash | the id of one commit | 9f3c1a2 |
| Linker | the build step that joins compiled packages into one executable | cmd/link |
-ldflags |
flags passed to the linker | -ldflags="-s -X main.version=1.4.2" |
-X |
linker flag: set a package-level string variable | -X main.version=1.4.2 |
| Build info | facts the go command records in the binary | -trimpath=true, GOOS=linux |
debug.ReadBuildInfo |
read the build info from inside the program | bi.GoVersion |
go version -m |
print a binary's build info | go version -m app |
| Symbol table | the list of names in a binary, for debuggers and tools | removed by -s |
| DWARF | debug information mapping machine code to source | removed by -w |
| Build constraint | a //go:build condition deciding if a file is compiled |
//go:build pro |
| Build tag | a word you switch on with -tags |
pro |
| File name suffix | _GOOS/_GOARCH in a file name selects the platform |
beep_windows.go |
| GOOS / GOARCH | the target operating system / processor architecture | linux, windows, darwin / amd64, arm64 |
| amd64 / arm64 | 64-bit Intel/AMD processors / 64-bit ARM processors | laptops / phones, Apple M chips, many servers |
| Cross-compiling | building for a different OS or processor | Windows ARM64 binary on Linux |
go list |
prints facts about packages, like which files are used | go list -f={{.GoFiles}} . |
go tool dist list |
lists every GOOS/GOARCH pair (48 in Go 1.24.7) | linux/arm64 |
| cgo | Go's bridge for calling C code | import "C" |
CGO_ENABLED |
turns cgo on (1) or off (0) | CGO_ENABLED=0 |
| C library (libc) | the standard C runtime library of the system | libc.so.6 |
| Dynamic linking | the binary loads shared libraries at start-up | needs ld-linux-x86-64.so.2 |
| Loader | the program that starts a dynamic binary and attaches its libraries | /lib64/ld-linux-x86-64.so.2 |
| Static binary | contains everything it needs, no shared libraries | CGO_ENABLED=0 build |
| ELF | the file format of Linux executables | read with debug/elf |
-trimpath |
removes local file system paths from the binary | no /home/raju/shop inside |
| Hash / SHA-256 | a fingerprint of data; any change changes it | sha256 a74d6c45... |
| Reproducible build | same inputs give byte-identical output | b and c match |
| Container | an isolated running program with its own file system and limits | docker run shop:1.4.2 |
| Container image | the packed file system a container starts from | shop:1.4.2 |
| Docker | a tool to build and run containers | Docker Engine 29.9.3 |
| Dockerfile | the recipe for building an image | FROM, COPY, RUN |
| Base image | the image a Dockerfile starts from | FROM scratch |
| Layer | the file changes one Dockerfile step adds; cached | RUN go mod download |
| Build argument | a value passed to a Docker build | --build-arg VERSION=1.4.2 |
| Multi-stage build | several FROM stages; the final one copies only what it needs |
build → scratch |
| scratch | Docker's completely empty image | FROM scratch |
| distroless | minimal images with only runtime dependencies, no shell | gcr.io/distroless/static-debian13 |
| Root / non-root | the all-powerful admin user / an ordinary user | USER 65532:65532 |
| Entry point | the command a container runs | ENTRYPOINT ["/shop"] |
| Port mapping | connecting a host port to a container port | -p 18080:8080 |
| Attack surface | everything an attacker could use or target | a shell inside the image |
| CA certificates | files used to check HTTPS servers' certificates | /etc/ssl/certs/ca-certificates.crt |
| x509 | the standard format of certificates; missing CAs show x509 errors | x509: certificate signed by unknown authority |
| tzdata | the time zone database | Asia/Kolkata |
| Archive | files packed into one, often compressed | shop_1.4.2_linux_arm64.tar.gz |
| Checksum file | the hashes of release files, for verifying downloads | checksums.txt |
| GoReleaser | a release automation tool driven by one YAML file | goreleaser release --clean |
| YAML | a text format for configuration using indentation | .goreleaser.yaml |
| CI (continuous integration) | automatic checks on every push and pull request | GitHub Actions |
| CD (continuous delivery) | automatically building and shipping what passed CI | image push, release |
| Pull request | a proposed change waiting for review and merge | "Fix the bill rounding" |
| Pipeline / workflow | the ordered list of CI steps | .github/workflows/ci.yml |
| Runner | the machine that runs a CI job | ubuntu-latest |
go vet |
reports suspicious code the compiler accepts | wrong Printf verb |
| Static analysis | checking code without running it | vet, staticcheck |
| staticcheck | an advanced Go linter | staticcheck ./... |
| Linter | a tool that flags bugs and style problems | staticcheck, golangci-lint |
| Data race | two goroutines access the same memory, at least one writes, without synchronisation | c.n++ from 50 goroutines |
| Race detector | -race: finds data races while the program runs |
WARNING: DATA RACE |
| Vulnerability | a security flaw in code | a CVE in a dependency |
| govulncheck | reports known Go vulnerabilities your code actually reaches | govulncheck ./... |
Summary
- Stamp the version at build time:
var version = "dev"+go build -ldflags "-X main.version=1.4.2"(typos are silently ignored, so check it).debug.ReadBuildInfo/go version -mshow what the go command recorded. - Smaller binaries:
-s(implies-wsince Go 1.22) dropped 2.29 MB to 1.48 MB. - Build constraints (
//go:build pro,!pro) and file suffixes (_linux.go) pick the right code; two unguarded files gavebeep redeclared in this block. Cross-compile withGOOS/GOARCH. CGO_ENABLED=0makes a static binary that needs no libc; a cgo binary inscratchfails withexec /shop: no such file or directory.-trimpathremoves local paths; two such builds had the same SHA-256: a reproducible build.- Multi-stage Docker: build in a Go image, ship only the binary
FROM scratch(7.87 MB vs 518 MB), as user 65532, with no shell inside; distroless static (~2 MiB) adds CA certificates and tzdata. - GoReleaser turns a tag into binaries for every target, archives and checksums from one YAML file.
- CI on every change:
go vet(caught a wrong%d), staticcheck,go test -race(caughtWARNING: DATA RACE), govulncheck, then the image.
Next episode: Running Go in the cloud and Kubernetes: container CPU and memory limits, GOMAXPROCS in containers, GOMEMLIMIT, liveness and readiness probes, SIGTERM and graceful shutdown, scaling, serverless Go.