Project Layout, golangci-lint, Makefile, Docker & Multi-Binary Builds
"Initially, it's recommended placing such packages into a directory named internal; this prevents other modules from depending on packages we don't necessarily want to expose and support for external uses." — "Organizing a Go module", go.dev/doc/modules/layout
Summary: a Go project is a module (one go.mod) holding packages; where you put directories decides what can be imported, what can be built into separate binaries and what a linter or a Dockerfile has to know. This chapter takes a service from "one main.go" to a repository that builds several binaries reproducibly, is linted and vulnerability-scanned in CI and ships as a small container. Focus: cmd/, internal/ and the pkg/ debate, flat layout for small services, multi-module repos and go.work, package naming, go vet, staticcheck and golangci-lint v2 (.golangci.yml, linters, formatters, exclusions), Makefile targets, go build flags (-ldflags -X, -trimpath, CGO_ENABLED=0, GOOS/GOARCH), version stamping and buildvcs, go generate, embed, build tags, the go and toolchain directives and GOTOOLCHAIN, vendoring and go mod verify, govulncheck, multi-stage Dockerfiles, CI with setup-go, pre-commit hooks, semantic versioning and tags. Learning goal: Lay out a new Go service in ten minutes without cargo-culting a template, say why internal/ matters and pkg/ usually does not, write a .golangci.yml you can defend, and turn git tag v1.4.0 into a static, stamped, scanned binary and a minimal image that anyone can rebuild bit for bit.
This page owns the shape of a repository and the commands around it. It does not re-teach its neighbours: what a module, a package and go run/go build are is in Toolchain, Modules & Packages, writing the tests that CI runs is in Testing & Benchmarking, the interfaces that make packages replaceable are in Mocking with Interfaces & DI, flags, environment variables and slog inside main are in CLI Flags, Env & Logging, a full HTTP service using this layout is built in A REST API in Go, and several binaries talking to each other are in Microservices project. The container platform around the image is in Containers & Kubernetes and the supply-chain view of scanning and signing is in Secure SDLC & Incident Response.
Facts below were checked against the Go documentation on go.dev ("Organizing a Go module", the module reference, "Go Toolchains", the go command and linker help), the Go 1.4, 1.11, 1.13, 1.14, 1.16, 1.17, 1.18, 1.20, 1.21, 1.24, 1.25, 1.26 and 1.27 release notes, the Go blog posts on reproducible toolchains and govulncheck, the golang-standards/project-layout README and its issue 117, Ben Johnson's "Standard Package Layout", the golangci-lint v2 reference configuration and migration guide, staticcheck.dev, the Docker multi-stage and cache documentation, the distroless README and the actions/setup-go and golangci-lint-action READMEs. pkg.go.dev returns 403 to scripted fetches, so API facts come from go.dev/src and the go help texts. Snippets declare go 1.24 and pin golang.org/x/sync v0.19.0, whose own go.mod declares go 1.24.0 (v0.20.0 declares go 1.25.0; both files are saved in the sources folder). Every command output in the lab was produced on macOS (Apple silicon) with Go 1.27.4, golangci-lint v2.15.0, staticcheck 2026.2.2 and govulncheck v1.1.4; the Docker lab was not run.
Page map
| If you are looking for | Go to |
|---|---|
| Every term of this chapter in one table | Everything in one minute |
| Why layout and build commands deserve a chapter | Why it exists |
| Which Go release added what | Where it comes from |
| A before/after of a whole project | Go |
go.mod at root, package names | Module and package naming |
| A single-package service | Flat layout |
cmd/ and a thin main | cmd/ |
internal/ and who may import what | internal/ |
Whether to create pkg/ | The pkg/ debate |
| What golang-standards/project-layout is and is not | golang-standards criticism |
| Packages by feature, Ben Johnson's rules | Organising packages |
Several modules, go.work | Multi-module repos and go.work |
go vet, staticcheck | go vet and staticcheck |
.golangci.yml, default, enable, settings | golangci-lint v2 |
errcheck, gosec, revive, gocritic, exhaustive ... | The linters worth knowing |
gofmt, goimports, gofumpt | Formatters |
//nolint, exclusions, new-from-rev | Suppressing without lying |
make build test lint run docker | Makefile |
-ldflags -X, -trimpath, CGO_ENABLED=0 | Build flags |
GOOS, GOARCH, cross-compilation | Cross-compilation |
Version in the binary, buildvcs, go version -m | Version stamping |
go build ./cmd/..., go install | Multi-binary builds |
go generate, //go:embed, //go:build | Generate, embed, build tags |
go line, toolchain line, GOTOOLCHAIN | go directive and toolchain |
go mod vendor, go mod verify, GOFLAGS=-mod=vendor | Dependencies |
govulncheck | Vulnerability scanning |
| Same bytes from the same commit | Reproducible builds |
| Dockerfile, distroless, scratch | Multi-stage Dockerfile |
| GitHub Actions, caches | CI |
pre-commit | Pre-commit hooks |
Tags, v2 import paths | Semantic versioning and tags |
| Exact error texts and exit codes | Mechanics |
| Typical problems and their fixes | Solving the classic problems |
| Which layout for which project | Choosing |
| One service to many services | In architecture |
| Reproduce the outputs on your machine | Lab |
| Composer, Pint, PHPStan, Sail compared | For PHP/Laravel developers |
Everything in one minute
What goes where. One rule decides most of it: a directory is a package, a module is a tree of packages with one go.mod at its root.
| You are building | Layout | Why |
|---|---|---|
| A library other people import | go.mod at root, package files in the root, sub-packages in directories, internal/ for helpers | The import path is the product; the root package is import "github.com/you/lib" |
| A tiny tool or one-file service | go.mod and main.go (flat layout for small services) | Nothing to separate yet; the Go docs start here |
| A service with one binary | cmd/<name>/main.go plus internal/... | main stays tiny; logic is testable and private |
| A service with several binaries | cmd/api, cmd/worker, shared internal/... | go build ./cmd/... builds them all from one module |
| A library plus its CLI | Root package for the library, cmd/<tool> for the command | go install github.com/you/lib/cmd/tool@latest works |
| Many deployable units with different release cycles | One module each, a go.work for local development | Independent versions, independent dependency graphs |
The commands you will type every day.
| Need | Command | What it does |
|---|---|---|
| Build everything | go build ./... | Compiles every package; discards the result |
| Build all binaries into a directory | go build -o bin/ ./cmd/... | Writes one executable per main package |
| Static, stamped, path-free binary | CGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X pkg.Version=v1.4.0" ./cmd/api | The release recipe |
| Cross-compile | GOOS=linux GOARCH=arm64 go build ./cmd/api | Another OS and CPU from your laptop |
| See what is inside a binary | go version -m bin/api | Go version, module, dependencies, build flags, VCS revision |
| Lint | golangci-lint run ./... | All enabled linters in one pass |
| Format | golangci-lint fmt ./... | The formatters from the formatters: section |
| Generate | go generate ./... | Runs every //go:generate line |
| Vendor / verify | go mod vendor, go mod verify | Copy dependencies in-tree; check the module cache |
| Scan | govulncheck ./... | Known vulnerabilities your code actually reaches |
The linters and tools by job.
| Job | Tool | One-line promise |
|---|---|---|
| Compiler-adjacent correctness | go vet (govet) | Suspicious constructs: printf verbs, copied locks, lost cancels |
| Deeper static analysis | staticcheck (SAxxxx, Sxxxx, STxxxx, Uxxxx) | Bugs, simplifications, style, unused code |
| Unchecked errors | errcheck | A returned error was dropped |
| Dead code | unused, ineffassign | Unused identifiers; assignments never read |
| Style and naming | revive | The golint successor: exported comments, var-naming |
| Security | gosec | G401 weak hash, G304 file path from a variable, G306 file permissions |
| Opinionated diagnostics | gocritic | ifElseChain, exitAfterDefer, appendAssign, ... |
| Enum completeness | exhaustive | A switch on an enum names every constant |
| Formatting | gofmt, goimports, gofumpt | One canonical layout, import grouping, stricter rules |
The keyword index. Every term below is unpacked on this page; the right column says where.
| Term | Where |
|---|---|
cmd/ | cmd/ |
internal/ | internal/ |
pkg/ debate | The pkg/ debate |
go.mod at root | Module and package naming |
| multi-module repos | Multi-module repos and go.work |
go.work | Multi-module repos and go.work |
| package naming | Module and package naming |
| internal packages visibility | internal/ |
| flat layout for small services | Flat layout |
| golang-standards/project-layout criticism | golang-standards criticism |
| golangci-lint v2 config (.golangci.yml) | golangci-lint v2 |
| linters: govet, staticcheck, errcheck, revive, gosec, unused, ineffassign, gocritic, exhaustive | The linters worth knowing |
| formatters gofmt/goimports/gofumpt | Formatters |
go vet | go vet and staticcheck |
| Makefile targets (build, test, lint, run, docker) | Makefile |
| go build -ldflags -X version injection | Version stamping |
-trimpath | Build flags |
CGO_ENABLED=0 | Build flags |
| GOOS/GOARCH cross-compilation | Cross-compilation |
| multi-binary builds (go build ./cmd/...) | Multi-binary builds |
go install | Multi-binary builds |
go generate | Generate, embed, build tags |
embed | Generate, embed, build tags |
| Dockerfile multi-stage (golang:1.27 → distroless/scratch) | Multi-stage Dockerfile |
| build cache in CI | CI |
go mod vendor | Dependencies |
go mod verify | Dependencies |
GOFLAGS=-mod=vendor | Dependencies |
| reproducible builds | Reproducible builds |
buildvcs | Version stamping |
go version -m | Version stamping |
govulncheck | Vulnerability scanning |
| pre-commit hooks | Pre-commit hooks |
| CI (GitHub Actions setup-go) | CI |
| semantic versioning and tags | Semantic versioning and tags |
| go.mod go directive and toolchain directive | go directive and toolchain |
GOTOOLCHAIN | go directive and toolchain |
Why it exists
Go deliberately has few rules about where files live: a directory is a package, a go.mod marks a module, and that is all the compiler needs. Everything else is convention, and conventions drift. One team puts every file in the root, another copies a template with 20 empty folders, a third nests pkg/ four deep. Three months later nobody can answer "can I import this from the other service?", "which of these main.go files is the real one?" or "why does CI build a different binary than my laptop?". The layout and the build commands are where those answers are written down.
| Without a convention | With the layout and build recipe on this page |
|---|---|
| Any package can be imported by anyone, so every refactor is a breaking change | internal/ makes the compiler refuse outside imports |
One main per repo, or a Makefile that cds around | cmd/<name> per binary, go build ./cmd/... |
go vet on a good day, nothing on a bad one | One .golangci.yml, the same run locally and in CI |
| Version is a constant someone forgets to bump | -ldflags -X or VCS stamping: the binary knows its tag and commit |
| "Works on my machine": CGO, paths, Go version differ | CGO_ENABLED=0, -trimpath, the go/toolchain lines |
| 900 MB image with a compiler and a shell | Multi-stage build, one static file on distroless |
| Dependencies change under your feet | go.sum, go mod verify, optional vendoring, govulncheck |
| More files and tools to learn | Fewer arguments, fewer surprises |
An everyday picture. A restaurant kitchen has a prep area, a pass and a delivery door. Raw ingredients (dependencies) come in through one inspected door (go.sum, go mod verify), cooks work in stations (packages) whose cupboards are private to the kitchen (internal/), the menu card (the public API) is short, and what leaves is a sealed, labelled box (a stamped static binary) rather than the whole kitchen. A layout is the floor plan; the Makefile is the order of service.
Three common misunderstandings, up front
- "Go has an official standard layout with
cmd/,pkg/,internal/,api/,configs/..." It does not. The Go team documents a handful of shapes ("Organizing a Go module"); the folder zoo in golang-standards/project-layout says in its own README that it is "NOT an official standard defined by the core Go dev team". - "
internal/is a naming convention." It is enforced by thegocommand: an import from outside the tree fails to compile withuse of internal package ... not allowed. - "A linter config is a list of everything you can turn on." Enabling all of golangci-lint (
default: all) buys style noise and a CI that can break whenever the tool adds a linter. A short, justified list wins.
Where it comes from
Early Go projects lived in a single GOPATH tree, where the import path was the directory path under src/, so layout questions were mostly answered by the toolchain. The pieces of today's practice arrived one release at a time, and knowing the release tells you which feature a team on an older toolchain cannot use.
| Release | What arrived | Why it matters here |
|---|---|---|
| Go 1.4 | Internal packages: the go command refuses imports of .../internal/... from outside the tree rooted at the parent of internal | The only access control above "exported or not" |
| Go 1.11 | Preliminary module support ("an alternative to GOPATH with integrated support for versioning") | go.mod at the root; projects leave GOPATH |
| Go 1.13 | -trimpath build flag | Binaries without your home directory in them |
| Go 1.14 | A top-level vendor/ is used by default when go.mod says go 1.14 or higher | GOFLAGS=-mod=vendor becomes automatic |
| Go 1.16 | embed package and //go:embed; go install pkg@version; build commands stop editing go.mod | Files inside the binary; installable tools; reproducible module state |
| Go 1.17 | //go:build lines understood by the go command; gofmt syncs them with // +build | The current build-constraint syntax |
| Go 1.18 | Version control information stamped into binaries (-buildvcs=false opts out); workspaces (go work) | go version -m shows the commit; multi-module development |
| Go 1.21 | The go line becomes a requirement; toolchain selection (GOTOOLCHAIN); the first toolchain with perfectly reproducible builds | go/toolchain directives; same input, same bytes |
| Go 1.24 | tool directives in go.mod (go tool); the main module version in the binary comes from the VCS tag, +dirty when uncommitted | No tools.go hack; -version shows v1.4.0 with no flags |
| Go 1.25 | ignore directive in go.mod; updating the go line no longer adds a toolchain line | Fewer noisy diffs |
| Go 1.26 | go mod init writes a lower go version (1.(N-2).0); go fix rebuilt on the go vet analysis framework | New modules accept older toolchains |
| Go 1.27 | go test runs the stdversion vet check by default; go mod tidy merges duplicate require blocks (for go 1.27 modules) | CI catches too-new standard library calls |
Outside the Go releases, three documents shaped the debate. Ben Johnson's "Standard Package Layout" argued for a root package of domain types and sub-packages grouped by dependency. The golang-standards/project-layout repository collected the folders large projects tended to have, and in April 2021 Russ Cox opened its issue 117, "this is not a standard Go project layout". The Go team's own page "Organizing a Go module" now answers the question with six small shapes. The linting side moved too: golangci-lint v2 (current release v2.15.0 at the time of writing) changed the configuration format (version: "2", separate linters and formatters, exclusions), merged stylecheck and gosimple into staticcheck, and moved gofmt, goimports, gofumpt and gci to formatters, as its migration guide documents. govulncheck reached v1.0.0 on 13 July 2023.
Go
Before
A service that works: one file, a hard-coded version string, a global map, ignored errors, and a main that a test can only exercise by running the whole program. It has no way to ship two binaries, no private packages and four lint findings waiting.
// Package main is the "before": one file that does everything. It works, but
// nothing here can be tested, versioned, linted cleanly or reused by a second
// binary.
package main
import (
"fmt"
"net/http"
"os"
)
// version is hard-coded: every release needs a source edit.
var version = "1.0.0"
// db is a package-level global that every handler reaches into.
var db map[string]string
func main() {
db = map[string]string{"greeting": "hello"}
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// The write error is ignored (errcheck would flag this).
fmt.Fprintf(w, "%s (v%s)\n", db["greeting"], version)
})
// The server error is ignored too, and main cannot be called from a test.
http.ListenAndServe(":"+port, nil)
}After
The same module restructured: a tiny cmd/api/main.go that delegates to a testable run, shared code in internal/, a second binary under cmd/worker, configuration embedded with //go:embed, and a version package whose variables the linker overwrites. The tree:
go.mod go.sum Makefile Dockerfile .golangci.yml
cmd/api/main.go package main: flags, signal context, run()
cmd/worker/main.go package main: second binary, same module
internal/app/ HTTP handlers, no globals
internal/config/ embedded defaults + environment overrides
internal/version/ -ldflags -X targets + debug.ReadBuildInfo fallback
internal/role/ go:generate example
internal/migrations/ embedded SQL files
internal/debugmode/ //go:build debugmode
internal/tools/genrole/ the generator itself
lintdemo/bad lintdemo/good deliberately broken vs clean code for the lintersThe entry point is a function that takes its inputs as arguments, so tests call it without starting a process:
// Command api serves the HTTP application. main stays tiny: all behaviour is in
// run, which takes its inputs as arguments so a test can call it.
package main
import (
"context"
"errors"
"flag"
"fmt"
"io"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"academy/project-layout-linting-build/internal/app"
"academy/project-layout-linting-build/internal/config"
"academy/project-layout-linting-build/internal/version"
)
func main() {
if err := runMain(); err != nil {
fmt.Fprintln(os.Stderr, "api:", err)
os.Exit(1)
}
}
// runMain owns the signal context so that its deferred stop always runs
// before main calls os.Exit.
func runMain() error {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
return run(ctx, os.Args[1:], os.LookupEnv, os.Stdout)
}
func run(ctx context.Context, args []string, lookup func(string) (string, bool), stdout io.Writer) error {
fs := flag.NewFlagSet("api", flag.ContinueOnError)
showVersion := fs.Bool("version", false, "print version information and exit")
if err := fs.Parse(args); err != nil {
return err
}
info := version.Get()
if *showVersion {
_, err := fmt.Fprintln(stdout, info.String())
return err
}
cfg, err := config.Load(lookup)
if err != nil {
return err
}
srv := &http.Server{
Addr: cfg.Addr,
Handler: app.Handler(cfg, info),
ReadHeaderTimeout: 5 * time.Second,
}
errc := make(chan error, 1)
go func() { errc <- srv.ListenAndServe() }()
select {
case err := <-errc:
return err
case <-ctx.Done():
shutdownCtx, cancel := context.WithTimeout(context.Background(), time.Duration(cfg.ShutdownSecs)*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil && !errors.Is(err, http.ErrServerClosed) {
return err
}
return nil
}
}package main
import (
"bytes"
"context"
"strings"
"testing"
"time"
)
func noEnv(string) (string, bool) { return "", false }
func TestRunVersionFlag(t *testing.T) {
var out bytes.Buffer
if err := run(context.Background(), []string{"-version"}, noEnv, &out); err != nil {
t.Fatal(err)
}
if !strings.Contains(out.String(), "commit=") {
t.Fatalf("version output = %q", out.String())
}
}
func TestRunBadFlag(t *testing.T) {
if err := run(context.Background(), []string{"-nope"}, noEnv, &bytes.Buffer{}); err == nil {
t.Fatal("want an error for an unknown flag")
}
}
func TestRunStopsOnContextCancel(t *testing.T) {
lookup := func(k string) (string, bool) {
if k == "APP_ADDR" {
return "127.0.0.1:0", true
}
return "", false
}
ctx, cancel := context.WithCancel(t.Context())
done := make(chan error, 1)
go func() { done <- run(ctx, nil, lookup, &bytes.Buffer{}) }()
time.Sleep(50 * time.Millisecond)
cancel()
select {
case err := <-done:
if err != nil {
t.Fatalf("graceful stop returned %v", err)
}
case <-time.After(5 * time.Second):
t.Fatal("run did not return after cancel")
}
}// Command worker is the second binary of the module. It shares internal/version
// and internal/config with cmd/api, and `go build ./cmd/...` builds both.
package main
import (
"context"
"fmt"
"io"
"os"
"os/signal"
"syscall"
"time"
"academy/project-layout-linting-build/internal/version"
"golang.org/x/sync/errgroup"
)
func main() {
if err := runMain(); err != nil {
fmt.Fprintln(os.Stderr, "worker:", err)
os.Exit(1)
}
}
func runMain() error {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
return run(ctx, os.Stdout, 2)
}
// run starts n tick loops that stop together when ctx ends.
func run(ctx context.Context, out io.Writer, n int) error {
if _, err := fmt.Fprintln(out, "worker", version.Get().Version); err != nil {
return err
}
g, ctx := errgroup.WithContext(ctx)
for i := 0; i < n; i++ {
g.Go(func() error {
t := time.NewTicker(10 * time.Millisecond)
defer t.Stop()
for {
select {
case <-ctx.Done():
return nil
case <-t.C:
}
}
})
}
return g.Wait()
}The Go angle
Go keeps the toolchain, the package system and the build in one binary: go build, go test, go vet, go generate, go install, go mod and go version -m all read the same go.mod and the same directory tree, so a layout is "right" when those commands work from the repository root without arguments other than ./.... There is no build file language to learn (the Makefile is optional glue), no separate dependency manager, and the resulting artefact is usually one statically linked file. The price is that the conventions live in documents and habits, not in a framework, so a team has to write them down once. This chapter is that once.
The concept catalogue
Module and package naming, go.mod at root Must-know
In plain words: The module path in go.mod is the prefix of every import path in the repository, and the directory name is the package's address. A package's own name is what you write after package, and callers see it at every use (version.Get()), so it should be short, lowercase and say what the package provides.
Common misunderstanding: "The module path must be a URL that exists." It only has to be unique, and it must look like a host name (github.com/acme/shop) if anyone else will ever go get it. Private code often uses a company domain. The snippet module uses academy/... on purpose, and the lab shows the one place that bites (gofumpt treats a first element without a dot as the standard library).
Definition: go.mod at root means the file sits at the top of the repository, next to cmd/ and internal/, and module github.com/acme/shop is its first directive. The Go docs say the package name of a library "matches the last path component of the module name". Package naming rules from Effective Go and the Go blog: no underscores or mixedCaps, no util/common/base grab-bags, the package name is not repeated in its identifiers (http.Server, not http.HTTPServer), and the directory name equals the package name except for main.
1 go mod init github.com/acme/shop module github.com/acme/shop, go 1.2x line written
2 mkdir -p internal/ledger import path github.com/acme/shop/internal/ledger
3 package ledger callers write ledger.Post(...)
4 mkdir cmd/api; package main import path never imported: it is a programReal scenario: a team renames utils/ into internal/clock, internal/slug, internal/retry; a library moves from github.com/old/x to github.com/new/x and needs a module change plus a redirect; a monorepo service has module company.example/platform/billing and is imported with that exact prefix by every sibling.
| Name | Verdict | Why |
|---|---|---|
package user in internal/user | Good | Short, matches the directory, reads as user.Service |
package userservice | Weak | Stutters: userservice.UserService |
package utils, package common | Avoid | Says nothing; becomes a dumping ground and an import cycle magnet |
package user_store | Wrong | Underscores are not idiomatic Go |
Module path github.com/acme/shop/v2 for the second major version | Required form | The /v2 suffix is part of the module path and import paths; the package clause stays package shop (see semver) |
Fix / how to use it: go mod init <path> once at the root; never nest a second go.mod unless you want a second module (multi-module); rename packages, not just directories. Toolchain, Modules & Packages covers the mechanics of go mod init and imports.
Flat layout for small services Must-know
In plain words: A small service can be one directory: go.mod, a few .go files that all say package main, and tests. That is a complete, valid project and the Go docs start there.
Common misunderstanding: "A real project needs cmd/, internal/ and pkg/ from day one." Empty folders are noise. Ben Johnson reports that a monolithic package "can actually work very well for small applications" and that he has "seen this work for applications up to 10K SLOC"; the golang-standards README itself says its layout "is an overkill" for a proof of concept and that "a single main.go file and go.mod is more than enough".
Definition: the Go docs list "Basic command": go.mod at the root and files that declare package main, installable with go install github.com/someuser/modname@latest. Split when a second binary appears, when you need a package that must not be importable, or when a file group has its own tests and vocabulary.
1 main.go func main() { run(...) }
2 server.go handlers
3 store.go database access
4 server_test.go httptest-based tests
5 go.mod module github.com/acme/hello (the whole project)Real scenario: a webhook receiver; a cron-job binary; an internal admin tool; a prototype that may be thrown away next week.
| Signal | Stay flat | Split |
|---|---|---|
| One binary, one team | Yes | No |
A second main appears | No | cmd/<name> each |
| Code you do not want others to import | No | Move it under internal/ |
| Files > ~20 in one directory with distinct vocabularies | No | One package per idea |
| Library consumers exist | No | Root package = public API, helpers in internal/ |
Fix / how to use it: start flat, keep main thin (a run(ctx, args, env, stdout) error function) so the later move into internal/ is a cut and paste.
cmd/ and the thin main Must-know
In plain words: cmd/ holds one directory per executable. Each directory is a package main whose main only reads flags and environment, builds dependencies and calls into internal/.
Common misunderstanding: "Business logic can live in main because it is only used there." Code in package main cannot be imported by other packages, and a test that calls main() itself is inconvenient and unsafe (it blocks on a server and may call os.Exit), so it tempts you into globals. The pattern in the snippet (run with explicit inputs, runMain owning the signal context so a deferred stop() runs before os.Exit) keeps main to four lines and lets go test drive the program, including -version and graceful shutdown.
Definition: "A common convention is placing all commands in a repository into a cmd directory; while this isn't strictly necessary in a repository that consists only of commands, it's very useful in a mixed repository that has both commands and importable packages" ("Organizing a Go module"). The binary is named after the directory: go build ./cmd/api yields api. The same page shows the server project shape: logic in internal/, commands in cmd/api-server, non-Go directories alongside.
1 go build -o bin/ ./cmd/... api, worker written to bin/
2 go install ./cmd/... both installed into $GOBIN
3 go install github.com/acme/shop/cmd/api@v1.4.0 installed by anyone, no checkoutReal scenario: cmd/api and cmd/worker sharing a queue package; cmd/migrate that applies embedded SQL and exits; cmd/seed for local data; a CLI next to the library it wraps.
| Concern | Lives in cmd/<name> | Lives in internal/ |
|---|---|---|
| Parsing flags, reading env | Yes | Config structs and defaults |
| Signal handling, exit codes | Yes | No |
| Wiring (construct DB, logger, server) | Yes | Constructors |
| Handlers, domain rules, SQL | No | Yes |
| Build-time variables | No | internal/version |
Fix / how to use it: keep each main.go under ~60 lines; if two commands share wiring, put the wiring in an internal/ package, not in a third main. See CLI Flags, Env & Logging for flag and slog setup.
internal/ and who may import what Must-know
In plain words: A directory named internal is a "private" door: only code inside the tree that contains internal may import what is behind it. Anyone whose import path is outside that prefix gets a compile error. That lets you refactor those packages freely.
Common misunderstanding: "internal/ hides code from my other modules in the same repository." It hides it from every package whose import path does not start with the parent of internal. Visibility follows import-path prefixes, not repositories or modules: a separate module whose path lies under the same prefix (example.com/shop/tools importing example.com/shop/internal/x) is allowed, while a module with an unrelated path (example.test/app) is not, even inside the same go.work workspace.
Definition: the Go 1.4 notes: "When the go command sees an import of a package with internal in its path, it verifies that the package doing the import is within the tree rooted at the parent of the internal directory." go help packages gives the example: example.com/m/foo/internal/baz can be imported by example.com/m/foo, .../foo/bar and .../foo/quux, but not by example.com/m/crash/bang. An internal directory may sit at any depth, not only at the root.
1 github.com/acme/shop/internal/ledger defined
2 github.com/acme/shop/cmd/api imports it -> ok (prefix github.com/acme/shop)
3 github.com/acme/shop/billing imports it -> ok
4 example.test/app imports it -> error
5 use of internal package github.com/acme/shop/internal/ledger not allowedReal scenario: a payments module that exposes payments.Charge but keeps its provider adapters in internal/stripe; a service where internal/store can change schema access without a major version; a library whose helper package was published by accident and could not be removed (the usual argument for starting private).
| Where | Importable by | Use for |
|---|---|---|
internal/x at module root | Everything in this module | Shared private code (default home) |
billing/internal/x | Only billing/... | Code private to one subtree |
x (no internal) | Anyone who can fetch the module | The public API you promise to keep |
vendor/x | Same rules as internal for the vendored tree | Copied dependencies |
Fix / how to use it: default new packages to internal/; promote one to a public path only when an outside user asks and you accept the compatibility promise. The recommendation in the Go docs is to keep "packages in internal as much as possible".
The pkg/ debate Important
In plain words: pkg/ is a folder some projects use for "code that other projects may import". The Go tool gives it no meaning; it is only a name.
Common misunderstanding: "pkg/ is required, or at least official." It is neither. Russ Cox wrote in issue 117 that "the vast majority of packages in the Go ecosystem do not put the importable packages in a pkg subdirectory". The cost is a longer import path and one more directory level; the benefit is a visual signal. golang-standards' own README concedes that "internal directory is a better way to ensure your private packages are not importable because it's enforced by Go" and that the pkg layout is "not universally accepted and some in the Go community don't recommend it".
Definition: with pkg/, public packages live at module/pkg/name; without it they live at module/name. Neither changes semantics. A module that is an application (a server) usually has nothing to export, so it needs neither pkg/ nor public packages; a library keeps its API in the root and sub-directories.
1 application: cmd/api, internal/... no pkg/ needed: nothing is exported
2 library: go.mod, client.go, auth/, internal/ API at the root, no pkg/
3 mixed repo: pkg/ or root packages + cmd/ + internal/ pkg/ optional, pick one and stayReal scenario: a large open-source project with pkg/ inherited from Kubernetes-era habits; a company monorepo where pkg/ means "shared by services, not by the world"; a new service that starts with pkg/ out of a template and has 14 empty subfolders.
| Choice | Pro | Con |
|---|---|---|
No pkg/ | Shorter imports; matches most of the ecosystem | Public and private packages differ only by internal/ |
pkg/ | One glance tells you what is public | Extra level; implies a promise internal already encodes |
Everything in internal/ | Maximum freedom | Cannot be imported by your own second module |
Fix / how to use it: do not create pkg/ for an application. If a library genuinely exports many packages, put them at the root or under a short domain name and keep helpers in internal/.
golang-standards/project-layout and its criticism Important
In plain words: golang-standards/project-layout is a popular GitHub repository listing folders (/cmd, /internal, /pkg, /api, /configs, /build, /deployments, /scripts, /vendor...) found in large Go projects. It sounds official because of its organisation name; it is not.
Common misunderstanding: "If I do not match it I am not following the Go standard." Its README says it is "NOT an official standard defined by the core Go dev team" and points to "Organizing a Go module" on go.dev. Issue 117 (opened by Russ Cox on 9 April 2021) says the README's own description, "a set of common historical and emerging project layout patterns", "is not accurate" and that the layout is "very complex, and Go repos tend to be much simpler". Other maintainers in the thread (rakyll, henvic and others) reported newcomers "trying to 'fix' their layout" because of it.
Definition: treat it as a catalogue of folders for non-Go assets (OpenAPI files, deployment manifests, scripts) that you adopt one at a time when you have the asset, not as a template. The Go-specific part that matters is cmd/ and internal/, both in the official doc.
1 git clone template; ls cmd internal pkg api configs build deployments scripts test ...
2 rm -r (everything you do not use today)
3 keep: go.mod, cmd/<name>, internal/<pkgs>, Makefile
4 add later: deploy/ when a Dockerfile appears, migrations/ when SQL appearsReal scenario: a code review that says "move this to /pkg" with no reason; a student project with eleven empty folders; an interview answer that recites the list instead of the trade-off.
| Folder in the template | Needed when |
|---|---|
/cmd, /internal | Almost always for services (both in the official doc) |
/pkg | Rarely; see the debate |
/api | You have OpenAPI or protobuf definitions |
/configs, /deployments, /build, /scripts | You have those files; name them deploy/ or scripts/ as you like |
/vendor | You vendor dependencies (deps) |
/src | Never (confuses people with the old GOPATH src) |
Fix / how to use it: read "Organizing a Go module" first, copy folders only on demand, and write the decision in the repository's README so reviewers argue with the document.
Organising packages: root domain, adapters, main Important
In plain words: Inside internal/, group code by what it depends on, not by technical type. Put plain domain types in one package, one adapter package per external system (PostgreSQL, HTTP, Redis), and let main connect them.
Common misunderstanding: "models/, controllers/, services/ is the clean way." Ben Johnson calls that Rails-style layout out for two problems: names like controller.UserController that repeat the package name, and circular dependencies when "different functional types may need to reference each other". Go forbids import cycles, so layers by type fight the compiler.
Definition: his four tenets: "Root package is for domain types", "Group subpackages by dependency", "Use a shared mock subpackage", "Main package ties together dependencies". The root package contains data types and interfaces (User, UserService) and "should not depend on any other package in your application"; postgres.UserService implements it; main wires. In a server module the "root" is an internal/<domain> package.
1 internal/order type Order, interface Store no imports of adapters
2 internal/postgres implements order.Store with database/sql imports internal/order
3 internal/http handlers use order.Store imports internal/order
4 cmd/api postgres.New(db) -> http.NewServer(store) wiring onlyReal scenario: swapping an in-memory store for PostgreSQL in tests; adding a cache that wraps order.Store; moving from REST to gRPC without touching the domain; breaking an import cycle between users and accounts.
| Layout | Cycle risk | Naming | Testability |
|---|---|---|---|
| One package | None (no imports) | Fine | Fine until ~10K lines (per Johnson) |
By type (models, handlers) | High | models.User, stutter | Mocks scattered |
By feature (user, billing) | Medium | Good | Good |
| Domain root + adapters | Low (one direction) | Good | Best: fakes implement the root interface |
Fix / how to use it: see Mocking with Interfaces & DI for the interface side; this chapter only decides where the files go.
Multi-module repos and go.work Important
In plain words: A repository can contain several go.mod files, each its own module with its own version and dependency list. go.work is a local file that tells the go command "treat these directories as one workspace while I develop".
Common misunderstanding: "A monorepo needs several modules." One module per repository is the default and the simplest; split when parts have different release cycles or very different dependencies. "In case the server repository grows packages that become useful for sharing with other projects, it's best to split these off to separate modules" (Go docs). And a workspace does not lift internal/: the lab shows use of internal package ... not allowed between two workspace modules whose paths do not share the prefix (a module under the same path prefix would be allowed).
Definition: go.work (Go 1.18) lists use directories; "most go subcommands that work with modules operate on the set of modules determined by the current workspace", while go mod init, go mod tidy, go mod vendor and go get "always operate on a single main module" (module reference). GOWORK=off disables it. Tag nested modules with a directory prefix, api/v1.2.0. Commit go.work only if every contributor needs it; many teams ignore it.
1 go work init ./lib ./app go.work: use ( ./app ./lib ), go 1.27.4 written by the tool
2 cd app && go run . app imports lib's public packages without a replace line
3 GOWORK=off go build ./... builds as a standalone module again: needs real versionsReal scenario: a library and its example app edited together; a monorepo with services/billing and services/search released separately; a private tools module so linters do not pollute the service's go.sum.
| Need | Use |
|---|---|
| One deployable, one team | One module |
| Edit a dependency locally | go.work (or a temporary replace) |
| Independent versions | A module per directory + prefix tags |
| Share code across modules | Public packages in a module, not internal/ |
Fix / how to use it: prefer one module; if you split, publish tags before removing replace directives, and run CI with GOWORK=off to prove each module builds alone.
go vet and staticcheck Must-know
In plain words: go vet ships with Go and finds code that compiles but is probably wrong (a Sprintf verb that does not match its argument, a copied mutex, a lost cancel function). staticcheck is a larger analyser maintained outside the distribution with checks for bugs (SA), simplifications (S), style (ST) and unused code (U).
Common misunderstanding: "go test already vets, so I do not need a separate run." go test runs only a small, high-confidence subset; since Go 1.27 it also runs stdversion. The full go vet ./... is a separate step, and in golangci-lint govet and staticcheck are both enabled by default.
Definition: go vet ./... reports and exits non-zero. staticcheck: staticcheck ./..., configured through staticcheck.conf or, inside golangci-lint v2, the staticcheck linter (which "merged" stylecheck and gosimple per the migration guide). In the lab, the same defect shows twice: go vet says fmt.Sprintf format %d has arg name of wrong type string, staticcheck says SA5009 and also U1000 for the unused function.
1 go vet ./... printf, lostcancel, copylocks, stdversion (1.27 test)
2 staticcheck ./... SA5009 wrong printf type, U1000 unused function
3 golangci-lint run both, plus errcheck, ineffassign, unused, ...Real scenario: a CI job that fails on copylocks after someone copied a struct with a sync.Mutex; a lostcancel finding before a context leak ships; staticcheck SA4006 finding a value that is never used.
| Tool | Ships with Go | Needs install | Typical cost |
|---|---|---|---|
go vet | Yes | No | Seconds |
| staticcheck | No | go install honnef.co/go/tools/cmd/staticcheck@latest | Seconds to a minute |
| golangci-lint | No | Install script, brew, or the action | Minutes cold, seconds cached |
Fix / how to use it: run go vet ./... in the vet Makefile target and let golangci-lint carry staticcheck; the other linters do not replace either.
golangci-lint v2 configuration (.golangci.yml) Must-know
In plain words: golangci-lint runs many linters in one pass, caches results and prints one report. You tell it which linters to use in .golangci.yml at the repository root.
Common misunderstanding: "Copy a big .golangci.yml from a famous project." golangci-lint's own configuration says: "This configuration file is not a recommendation. We intentionally use a limited set of linters". And a v1 file does not load in v2: the first key must be version: "2" and golangci-lint migrate converts old files.
Definition: top-level keys version, run (timeout, tests, build-tags, concurrency...), linters (default, enable, disable, settings, exclusions), formatters (enable, settings, exclusions), issues, severity, output. linters.default is standard (errcheck, govet, ineffassign, staticcheck, unused), all, none or fast. golangci-lint config verify checks a file, golangci-lint linters lists what is enabled, and by default run exits with code 1 when it finds issues (issues-exit-code, default 1).
# golangci-lint v2 configuration. The first key must be version: "2".
version: "2"
run:
timeout: 5m
tests: true
linters:
# "standard" = errcheck, govet, ineffassign, staticcheck, unused.
default: standard
enable:
- revive # style: exported comments, naming (replaces golint)
- gosec # security checks
- gocritic # opinionated bug/style/performance checks
- exhaustive # switch on an enum must name every constant
- errorlint # errors.Is/As and %w instead of == and %v
- bodyclose # unclosed http response bodies
- noctx # http requests without a context
settings:
govet:
enable:
- shadow
errcheck:
check-type-assertions: true
exhaustive:
default-signifies-exhaustive: false
revive:
rules:
- name: exported
- name: var-naming
- name: package-comments
exclusions:
# Generated files are matched by their "Code generated ... DO NOT EDIT" header.
generated: lax
rules:
# Tests may use weaker patterns.
- path: _test\.go
linters:
- gosec
paths:
- before # intentionally poor example
formatters:
enable:
- gofmt
- goimports
# gofumpt is a stricter gofmt. It is left out here on purpose: this module is
# named academy/..., a path without a dot in its first element, and gofumpt
# then sorts the module's own imports into the standard-library group,
# which fights goimports local-prefixes. A github.com/... module path does
# not have that problem.
# - gofumpt
settings:
goimports:
local-prefixes:
- academy/project-layout-linting-build1 golangci-lint config verify valid, or the key and line that are wrong
2 golangci-lint run ./... text report, exit 1 on findings
3 golangci-lint run --build-tags lintdemo ./lintdemo/bad/... include tagged files
4 golangci-lint cache clean forget cached resultsReal scenario: adopting the tool on an old service (use new-from-rev so only new code is judged); pinning the version in CI so an upgrade does not add linters overnight; excluding generated files; allowing weaker checks in tests.
default: | Behaviour | Use when |
|---|---|---|
standard | The five default linters, extend with enable | The sensible start |
none | Only what you list | You want results stable across upgrades |
all | Everything, then disable what you reject | Rarely; new linters appear with each release |
fast | Only linters flagged fast | Editor integration and pre-commit |
Fix / how to use it: start with standard plus revive, gosec, gocritic, exhaustive, errorlint, bodyclose, noctx (the snippet file), run golangci-lint config verify in CI and pin the version.
The linters worth knowing Must-know
In plain words: Each linter looks for one family of mistakes. You do not need 100; you need the dozen whose findings you would actually fix.
Common misunderstanding: "More linters means more quality." Every linter adds findings someone must triage, and style-only linters create churn. Choose by cost of the bug the linter prevents.
Definition: the real output of the snippet's lintdemo/bad package (12 findings from 9 linters) is the best tour:
//go:build lintdemo
// Package bad is compiled only with -tags lintdemo. It compiles, but each
// function trips a different linter, so a lint run shows what each one reports.
package bad
import (
"crypto/md5"
"fmt"
"io"
"os"
"academy/project-layout-linting-build/internal/role"
)
// Checksum uses a weak hash and ignores the error from os.ReadFile's caller.
func Checksum(path string) string {
data, _ := os.ReadFile(path)
sum := md5.Sum(data)
return fmt.Sprintf("%x", sum)
}
// Cleanup ignores the error returned by Remove.
func Cleanup(path string) {
os.Remove(path)
}
// Count assigns a value that is never read.
func Count(items []string) int {
n := len(items)
n = len(items) + 1
return n
}
func Exported() {}
// IsEOF compares an error with == instead of errors.Is.
func IsEOF(err error) bool {
return err == io.EOF
}
// UserLookup uses an underscore in a local name.
func UserLookup(user_id int) int {
return user_id
}
// Describe forgets one constant of the enum role.Role.
func Describe(r role.Role) string {
switch r {
case role.Guest:
return "guest"
case role.Member:
return "member"
}
return "?"
}
// Bad wraps a printf-style call with the wrong verb.
func Bad(name string) string {
return fmt.Sprintf("%d", name)
}
func helperNobodyCalls() {}
// Grade is an if-else chain that gocritic suggests turning into a switch.
func Grade(score int) string {
if score >= 90 {
return "A"
} else if score >= 80 {
return "B"
} else if score >= 70 {
return "C"
} else {
return "F"
}
}bad.go:25:11: Error return value of `os.Remove` is not checked (errcheck)
bad.go:39:9: comparing with == will fail on wrapped errors. Use errors.Is ... (errorlint)
bad.go:49:2: missing cases in expression switch: role.Admin (exhaustive)
bad.go:67:2: ifElseChain: rewrite if-else to switch statement (gocritic)
bad.go:8:2: G501: Blocklisted import crypto/md5: weak cryptographic primitive (gosec)
bad.go:18:13: G304: Potential file inclusion via variable (gosec)
bad.go:19:9: G401: Use of weak cryptographic primitive (gosec)
bad.go:60:22: printf: fmt.Sprintf format %d has arg name of wrong type string (govet)
bad.go:30:2: ineffectual assignment to n (ineffassign)
bad.go:35:1: exported: exported function Exported should have comment or be unexported (revive)
bad.go:43:17: var-naming: don't use underscores in Go names; ... (revive)
bad.go:63:6: func helperNobodyCalls is unused (unused)Real scenario: errcheck catching a dropped Close on a writer (lost data); gosec flagging G401/G501 for MD5 used for a password; exhaustive finding the new Admin role missing from a permission switch; bodyclose and noctx on an HTTP client without a context.
| Linter | Finds | Cost | Verdict |
|---|---|---|---|
govet | printf mismatches, copylocks, lostcancel | Low | Always on (default) |
staticcheck | SA bugs, S simplifications, ST style, U unused | Low | Always on (default) |
errcheck | Ignored error returns | Low | Always on (default) |
unused | Unused code | Low | Always on (default) |
ineffassign | Assignments never read | Low | Always on (default) |
revive | Exported comments, naming, many style rules | Medium (tunable) | On, with a short rule list |
gosec | Weak crypto, file inclusion, permissions, SQL string building | Medium | On for services; relax in tests |
gocritic | Diagnostics, style and performance tags | Medium | On with default tags |
exhaustive | Enum switches missing constants | Low | On if you use iota enums |
errorlint | == on errors, %v instead of %w | Low | Good |
bodyclose, noctx | Unclosed bodies, requests without ctx | Low | Good for HTTP clients |
contextcheck, containedctx | Context misuse (see context) | Medium | Optional |
Fix / how to use it: the lintdemo/good package is the clean twin: errors.Is, a returned error from Cleanup, a tagged switch, all enum constants named, SHA-256 and a #nosec G304 comment with a reason.
// Package good is the clean twin of lintdemo/bad: same behaviours, no findings.
package good
import (
"crypto/sha256"
"errors"
"fmt"
"io"
"os"
"academy/project-layout-linting-build/internal/role"
)
// Checksum hashes a file with SHA-256 and returns the read error.
func Checksum(path string) (string, error) {
data, err := os.ReadFile(path) // #nosec G304 -- the caller chooses the path; this is a demo helper
if err != nil {
return "", fmt.Errorf("checksum %s: %w", path, err)
}
return fmt.Sprintf("%x", sha256.Sum256(data)), nil
}
// Cleanup removes path and treats "already gone" as success.
func Cleanup(path string) error {
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("cleanup %s: %w", path, err)
}
return nil
}
// Count returns the number of items plus one.
func Count(items []string) int {
return len(items) + 1
}
// IsEOF reports whether err is, or wraps, io.EOF.
func IsEOF(err error) bool {
return errors.Is(err, io.EOF)
}
// UserLookup returns the id unchanged; the parameter uses camelCase.
func UserLookup(userID int) int {
return userID
}
// Describe names every role.Role constant, so exhaustive stays quiet.
func Describe(r role.Role) string {
switch r {
case role.Guest:
return "guest"
case role.Member:
return "member"
case role.Admin:
return "admin"
}
return "unknown"
}
// Grade maps a score to a letter with a tagged switch.
func Grade(score int) string {
switch {
case score >= 90:
return "A"
case score >= 80:
return "B"
case score >= 70:
return "C"
default:
return "F"
}
}Formatters: gofmt, goimports, gofumpt Important
In plain words: A formatter rewrites files into one canonical shape so diffs show only meaning. In golangci-lint v2 they are a separate section; golangci-lint fmt rewrites, fmt --diff only shows.
Common misunderstanding: "Formatters are linters." In v2 they moved out of linters: "The linters gci, gofmt, gofumpt, and goimports have been moved to the formatters section" (migration guide). The list is gci, gofmt, gofumpt, goimports, golines, swaggo.
Definition: gofmt is the canonical layout. goimports also adds and groups imports; local-prefixes puts your own module in a separate group. gofumpt is a stricter superset. In the lab, enabling gofumpt together with goimports and a module called academy/... produced findings that moved between runs, because a first path element without a dot looks like the standard library to gofumpt. With a real github.com/... path the problem does not exist, so the snippet's config leaves gofumpt as a comment.
1 golangci-lint fmt ./... rewrite files with gofmt + goimports
2 golangci-lint fmt --diff ./... print what would change, exit 0 and write nothing
3 golangci-lint run ./... formatters also report "File is not properly formatted"Real scenario: a pre-commit hook that formats before the commit; a CI job that runs fmt --diff and fails when the output is not empty; imports re-grouped so reviewers see std, third-party, local.
| Formatter | Adds | Notes |
|---|---|---|
gofmt | Canonical layout | Always |
goimports | Import add/remove and grouping, local-prefixes | Standard choice |
gofumpt | Stricter rules (empty lines, grouping std imports) | Watch dotless module paths |
gci | Explicit import sections | When you want fixed section order |
golines | Line-length wrapping | Optional |
Fix / how to use it: run make fmt before committing and make lint (which includes fmt --diff) in CI.
Suppressing findings without lying Important
In plain words: Sometimes a finding is a false alarm. Suppress it as narrowly as possible and say why.
Common misunderstanding: "A global exclude is cheaper than fixing." A directory-wide exclusion hides real bugs next to the false positive. The nolintlint linter exists to keep //nolint comments honest, and gocritic's whyNoLint asks for an explanation.
Definition: three levels. A line comment (//nolint:gosec // reason, or gosec's own #nosec G304), a rule in linters.exclusions.rules (by path and linter, as the snippet does for gosec in tests), and exclusions.paths / generated: lax for generated code. For legacy code, issues.new-from-rev: HEAD~1 (or new: true) shows only new issues: "much better don't allow issues in new code" than fixing everything at integration time.
1 //nolint:errcheck // best-effort close on shutdown one line, one linter, one reason
2 exclusions.rules: path _test\.go, linters gosec weaker rules in tests
3 exclusions.paths: before an intentional bad example
4 issues.new-from-rev: origin/main legacy code ratchetReal scenario: a generated protobuf file; a test using math/rand flagged by gosec; a 200k-line legacy service adopting the linter in a week.
| Mechanism | Scope | Risk |
|---|---|---|
//nolint:x // why | One line | Low if it has a reason |
exclusions.rules | Path plus linter | Medium |
exclusions.paths | Whole directory | High |
new-from-rev | Old code ignored | Debt remains, but cannot grow |
Fix / how to use it: enable nolintlint, require the reason, and review exclusions like code.
Makefile targets: build, test, lint, run, docker Must-know
In plain words: A Makefile is a short list of named commands so everyone, including CI, types the same thing: make build, make test, make lint, make run, make docker.
Common misunderstanding: "The Makefile is the build system." The build system is go build; make stores the flags. If CI cannot run the same target as a developer, the Makefile is lying. Also remember tabs: recipe lines must start with a tab.
Definition: the snippet's Makefile defines VERSION, COMMIT and DATE from Git (git describe --tags --always --dirty, git rev-parse --short HEAD, the commit time in UTC), composes LDFLAGS, and exposes help, build, test, lint, fmt, vet, generate, run, docker, vuln, vendor, verify, cross, clean. Targets that are not files are listed in .PHONY.
# Makefile for the academy/project-layout-linting-build module.
# Usage: make help | make build | make test | make lint | make run | make docker
MODULE := academy/project-layout-linting-build
BINS := api worker
BIN_DIR := bin
VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo dev)
COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo unknown)
# The commit time (not "now") keeps two builds of one commit byte-identical.
DATE ?= $(shell TZ=UTC git log -1 --format=%cd --date=format-local:%Y-%m-%dT%H:%M:%SZ 2>/dev/null || echo unknown)
PKG := $(MODULE)/internal/version
LDFLAGS := -s -w -X $(PKG).Version=$(VERSION) -X $(PKG).Commit=$(COMMIT) -X $(PKG).Date=$(DATE)
GOFLAGS_BUILD := -trimpath
.DEFAULT_GOAL := help
.PHONY: help build test lint fmt vet generate run docker vuln vendor verify cross clean
help: ## Show this help
@grep -E '^[a-z]+:.*## ' $(MAKEFILE_LIST) | awk -F':.*## ' '{printf "%-10s %s\n", $$1, $$2}'
build: ## Build every binary under cmd/ into ./bin
CGO_ENABLED=0 go build $(GOFLAGS_BUILD) -ldflags "$(LDFLAGS)" -o $(BIN_DIR)/ ./cmd/...
test: ## Run all tests with the race detector
go test -race -count=1 ./...
lint: ## Run golangci-lint (vet, staticcheck, errcheck, ...) and check formatting
golangci-lint run ./...
golangci-lint fmt --diff ./...
fmt: ## Rewrite files with the configured formatters
golangci-lint fmt ./...
vet: ## Run go vet
go vet ./...
generate: ## Run go generate and fail if the generated files changed
go generate ./...
git diff --exit-code -- internal/role/role_gen.go
run: build ## Build and run the API on :8080
./$(BIN_DIR)/api
docker: ## Build the container image
docker build --build-arg VERSION=$(VERSION) --build-arg COMMIT=$(COMMIT) --build-arg DATE=$(DATE) -t academy/api:$(VERSION) .
vuln: ## Scan source and dependencies for known vulnerabilities
govulncheck ./...
vendor: ## Vendor dependencies and verify the module cache
go mod vendor
go mod verify
verify: vet lint test vuln ## Everything CI runs
cross: ## Cross-compile static Linux and macOS binaries
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build $(GOFLAGS_BUILD) -ldflags "$(LDFLAGS)" -o $(BIN_DIR)/api-linux-amd64 ./cmd/api
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build $(GOFLAGS_BUILD) -ldflags "$(LDFLAGS)" -o $(BIN_DIR)/api-linux-arm64 ./cmd/api
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build $(GOFLAGS_BUILD) -ldflags "$(LDFLAGS)" -o $(BIN_DIR)/api-darwin-arm64 ./cmd/api
clean: ## Remove build output
rm -rf $(BIN_DIR)1 make build CGO_ENABLED=0 go build -trimpath -ldflags "..." -o bin/ ./cmd/...
2 make test go test -race -count=1 ./...
3 make lint golangci-lint run ./... && golangci-lint fmt --diff ./...
4 make verify vet lint test vuln (everything CI runs)Real scenario: a new hire runs make verify before the first pull request; CI calls make verify verbatim; a release script calls make cross VERSION=v1.4.0.
| Target | Command | Notes |
|---|---|---|
build | go build ... -o bin/ ./cmd/... | Static, stamped, trimmed |
test | go test -race -count=1 ./... | -count=1 skips cached results |
lint | golangci-lint run and fmt --diff | Fails on lint findings; fmt --diff output is checked for drift |
run | builds then starts bin/api | Local only |
docker | docker build --build-arg VERSION=... | Not run in this chapter's lab |
generate | go generate then git diff --exit-code | Fails if generated files are stale |
Fix / how to use it: keep targets one line each; put long logic in scripts or Go programs, not in Make syntax. Alternatives (just, task, mage) are fine; the point is one entry point.
go build flags: -ldflags -X, -trimpath, CGO_ENABLED=0 Must-know
In plain words: A few flags turn a developer build into a release build: no C library dependency, no local paths, a smaller file and a version inside.
Common misunderstanding: "-ldflags -X can set any variable." The linker doc: "This is only effective if the variable is declared in the source code either uninitialized or initialized to a constant string expression. -X will not work if the initializer makes a function call or refers to other variables." It sets strings only, and the name must be the full import path of the package plus the variable.
Definition: -ldflags '-s -w -X importpath.name=value': -s "Omit the symbol table and debug information", -w "Omit the DWARF symbol table". -trimpath "remove all file system paths from the resulting executable" (Go 1.13). CGO_ENABLED=0 disables cgo, so the result links no libc and is static; since Go 1.20 cgo is also off by default when no C compiler is found. go build -o bin/ ./cmd/... writes one executable per main.
1 CGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X academy/.../internal/version.Version=v1.4.0" -o bin/ ./cmd/...
2 file bin/api-linux-amd64 ELF 64-bit LSB executable, x86-64, statically linked
3 strings bin/api | grep $PWD 0 hits with -trimpath, 4 hits without (lab)Real scenario: a scratch image that fails to start because the binary was dynamically linked against glibc; a stack trace in production that leaks /Users/alex/...; a -X that silently did nothing because the package path was wrong.
| Flag | Effect | Trade-off |
|---|---|---|
CGO_ENABLED=0 | Static binary; pure-Go DNS/net | Packages that need C (some SQLite drivers) will not build |
-trimpath | No absolute paths in the binary | Stack traces show module paths, not local files |
-ldflags "-s -w" | Smaller file | No debugger symbols; pprof still works for names |
-X pkg.Var=val | Version, commit, date | Strings only; wrong path fails silently |
-tags x | Build constraints | See generate, embed, build tags |
-race | Race detector | Needs cgo; use for tests, not release binaries |
Fix / how to use it: put the flags in the Makefile and the Dockerfile once; test the injected value (bin/api -version) in CI.
Cross-compilation: GOOS and GOARCH Must-know
In plain words: Go compiles for another operating system and CPU by setting two variables. No emulator, no second machine.
Common misunderstanding: "Cross-compiling needs a toolchain per target." Not for pure Go with CGO_ENABLED=0. With cgo you need a C cross-compiler, which is why static builds are the default advice.
Definition: GOOS=linux GOARCH=arm64 go build ./cmd/api. go tool dist list prints the supported pairs (47 on this machine's Go 1.27.4). GOARM64, GOAMD64 select variants. Results of the Makefile's cross target (lab): ELF 64-bit LSB executable, x86-64, statically linked, ELF ... ARM aarch64, Mach-O 64-bit executable arm64.
1 GOOS=linux GOARCH=amd64 -> bin/api-linux-amd64 6656160 bytes
2 GOOS=linux GOARCH=arm64 -> bin/api-linux-arm64 6160544 bytes
3 GOOS=darwin GOARCH=arm64 -> bin/api-darwin-arm64 6302962 bytesReal scenario: building a Linux image on an Apple-silicon laptop; releasing binaries for four platforms from CI; an arm64 Kubernetes node pool next to amd64.
| Target | Variables | Notes |
|---|---|---|
| Linux server | GOOS=linux GOARCH=amd64 | The default for containers |
| Linux ARM | GOOS=linux GOARCH=arm64 | Graviton, Ampere, Raspberry Pi 4/5 |
| macOS Apple silicon | GOOS=darwin GOARCH=arm64 | Developer machines |
| Windows | GOOS=windows GOARCH=amd64 | Output gets .exe |
Fix / how to use it: in Docker, use docker buildx with --platform or build in CI per architecture; never ship a binary built for the wrong GOARCH.
Version stamping, buildvcs and go version -m Must-know
In plain words: Your binary should be able to say which tag and commit it came from. Go can write that in for you, or you can inject it yourself.
Common misunderstanding: "-ldflags -X is the only way." Since Go 1.18 the go command stamps VCS data, and since Go 1.24 it sets the main module version from the tag. Both come with caveats: a build outside the repository, in a Docker layer without .git, or with -buildvcs=false has nothing to stamp.
Definition: -buildvcs ("true", "false" or "auto"): by default information is stamped "if the main package, the main module containing it, and the current directory are all in the same repository"; -buildvcs=false omits it. Go 1.24: "A +dirty suffix will be appended if there are uncommitted changes." go version -m bin/api prints the module, dependencies and build settings including vcs.revision, vcs.time and vcs.modified. runtime/debug.ReadBuildInfo reads the same data at run time; internal/version in the snippet prefers -X values and falls back to it.
// Package version holds the build identity of a binary. The three variables
// are meant to be overwritten at link time:
//
// go build -ldflags "-X academy/project-layout-linting-build/internal/version.Version=v1.4.0"
//
// When they are not, Info falls back to the build information that the go
// command stamps into every binary (debug.ReadBuildInfo).
package version
import (
"fmt"
"runtime"
"runtime/debug"
)
// These are string variables initialised to constants, the only shape that
// the linker's -X flag can overwrite.
var (
// Version is a semantic version tag such as v1.4.0.
Version = "dev"
// Commit is the VCS revision the binary was built from.
Commit = "unknown"
// Date is the build or commit time in RFC 3339.
Date = "unknown"
)
// Info is the resolved identity of the running binary.
type Info struct {
Version string
Commit string
Date string
GoVersion string
Modified bool
}
// String renders Info on one line, for a -version flag.
func (i Info) String() string {
dirty := ""
if i.Modified {
dirty = " (modified)"
}
return fmt.Sprintf("%s commit=%s date=%s %s%s", i.Version, i.Commit, i.Date, i.GoVersion, dirty)
}
// Get returns the identity, preferring values injected with -ldflags -X and
// falling back to the vcs.* settings recorded by the go command (Go 1.18+).
func Get() Info {
info := Info{Version: Version, Commit: Commit, Date: Date, GoVersion: runtime.Version()}
bi, ok := debug.ReadBuildInfo()
if !ok {
return info
}
if info.Version == "dev" && bi.Main.Version != "" && bi.Main.Version != "(devel)" {
// Go 1.24+ stamps the main module version from the VCS tag.
info.Version = bi.Main.Version
}
for _, s := range bi.Settings {
switch s.Key {
case "vcs.revision":
if info.Commit == "unknown" {
info.Commit = s.Value
}
case "vcs.time":
if info.Date == "unknown" {
info.Date = s.Value
}
case "vcs.modified":
info.Modified = s.Value == "true"
}
}
return info
}package version
import (
"strings"
"testing"
)
func TestGetDefaults(t *testing.T) {
info := Get()
if info.GoVersion == "" {
t.Fatal("GoVersion must always be set")
}
if info.Version == "" {
t.Fatal("Version must never be empty")
}
}
func TestGetUsesInjectedValues(t *testing.T) {
// Simulate what -ldflags -X does: overwrite the package variables.
oldV, oldC := Version, Commit
t.Cleanup(func() { Version, Commit = oldV, oldC })
Version, Commit = "v1.4.0", "abc1234"
info := Get()
if info.Version != "v1.4.0" || info.Commit != "abc1234" {
t.Fatalf("injected values lost: %+v", info)
}
if !strings.HasPrefix(info.String(), "v1.4.0 commit=abc1234") {
t.Fatalf("unexpected String(): %q", info.String())
}
}
func TestStringMarksModified(t *testing.T) {
s := Info{Version: "v1", Commit: "c", Date: "d", GoVersion: "go1", Modified: true}.String()
if !strings.HasSuffix(s, "(modified)") {
t.Fatalf("dirty build not marked: %q", s)
}
}1 git tag v1.4.0; make build; bin/api -version
2 v1.4.0 commit=9d9483e date=2026-11-28T11:27:30Z go1.27.4 (-X values)
3 go build ./cmd/api; api -version (no -X: from buildinfo)
4 v1.4.0 commit=9d9483e074... date=...Z go1.27.4
5 echo '// edit' >> cmd/api/main.go; go build ... (dirty tree)
6 v1.4.0+dirty commit=9d9483e074... (modified)
7 go build -buildvcs=false ... (nothing to stamp)
8 dev commit=unknown date=unknown go1.27.4Real scenario: an incident where /version shows the exact commit that is running; a bug report that includes api -version; a security scan matching go version -m module versions against a database.
| Source | Gives | Needs | Fails when |
|---|---|---|---|
-ldflags -X | Any string you pass | A build script | Wrong import path, non-constant initialiser |
| VCS stamping (1.18+) | vcs.revision, vcs.time, vcs.modified | .git visible to the build | Docker without .git; -buildvcs=false |
| Main module version (1.24+) | v1.4.0 or v1.4.0+dirty | A tag on the commit | No tag: (devel) |
debug.ReadBuildInfo | All of the above at run time | Module-aware build | go run file.go style builds |
Fix / how to use it: pass -X in the Makefile and Dockerfile (the build context often has no .git), keep the vcs fallback for plain go build, add bin/ to .gitignore (the lab showed an untracked bin/ making a build modified=true), and expose /version plus -version.
Multi-binary builds and go install Must-know
In plain words: One module, many programs. go build ./cmd/... builds them all; go install puts them in $GOBIN (or $GOPATH/bin).
Common misunderstanding: "go build ./cmd/... produces binaries." With more than one main package, go build without -o compiles and discards the result (lab: exit 0, nothing written). Use -o bin/ (a directory) or go install.
Definition: go build -o bin/ ./cmd/... writes bin/api and bin/worker. go install ./cmd/... installs both. Go 1.16: go install example.com/cmd@v1.0.0 "build[s] and install[s] packages in module-aware mode, ignoring the go.mod file in the current directory", the recommended way to install tools. Since Go 1.24 the tool directive in go.mod plus go tool name replaces a tools.go file for linters pinned to the module.
1 go build ./cmd/... exit 0, nothing written (several mains)
2 go build -o bin/ ./cmd/... bin/api bin/worker
3 GOBIN=/tmp/gobin go install ./cmd/... api worker
4 go list ./cmd/... .../cmd/api .../cmd/workerReal scenario: a Dockerfile that builds only ./cmd/api while another builds ./cmd/worker from the same context; a release job uploading every binary in bin/; a developer installing a CLI from a tag with no clone.
| Command | Writes | Use |
|---|---|---|
go build ./... | Nothing | Compile check |
go build -o bin/ ./cmd/... | One file per main | Release or local build |
go build -o bin/api ./cmd/api | One named file | Dockerfile |
go install ./cmd/... | $GOBIN | Local tools |
go install mod/cmd/x@v1.2.3 | $GOBIN | Installing someone else's tool |
Fix / how to use it: build per binary in Docker, all at once in CI, and always set -o.
go generate, embed and build tags Important
In plain words: Three small features keep the repository honest: go generate regenerates code you would otherwise edit by hand, embed puts files inside the binary, and build tags choose which files compile.
Common misunderstanding: "go build runs go generate." It never does. Generated files are committed, and CI should run go generate ./... followed by git diff --exit-code to catch stale ones. Another: "embed can read files outside the package directory." Patterns cannot contain ..; the files must be in the package directory or below.
Definition: //go:generate command args anywhere in a package; go generate runs each line and sets GOPACKAGE and friends. import "embed" (blank import for string/[]byte) with //go:embed pattern before a variable of type string, []byte or embed.FS (Go 1.16). //go:build tag at the top of a file (Go 1.17; // +build is the old form gofmt keeps in sync). A tag is enabled with go build -tags name.
// Package role shows //go:generate. The String method lives in role_gen.go,
// written by internal/tools/genrole; `go generate ./...` regenerates it.
package role
// Role is a closed set of values, an iota enum.
type Role int
const (
// Guest can read public pages.
Guest Role = iota
// Member can read and write own data.
Member
// Admin can manage everything.
Admin
)
//go:generate go run ../tools/genrole -type=Role -out=role_gen.go Guest Member Admin// Command genrole is a miniature code generator: it writes a String method for
// an iota enum. It exists to show the go:generate workflow without a third-party
// dependency (the real tool for this job is golang.org/x/tools/cmd/stringer).
package main
import (
"bytes"
"flag"
"fmt"
"go/format"
"log"
"os"
)
func main() {
typeName := flag.String("type", "", "name of the enum type")
out := flag.String("out", "", "output file")
flag.Parse()
names := flag.Args()
if *typeName == "" || *out == "" || len(names) == 0 {
log.Fatal("usage: genrole -type=T -out=file.go Name1 Name2 ...")
}
pkg := os.Getenv("GOPACKAGE") // set by go generate
if pkg == "" {
log.Fatal("GOPACKAGE is empty: run this through go generate")
}
var b bytes.Buffer
fmt.Fprintf(&b, "// Code generated by genrole; DO NOT EDIT.\n\npackage %s\n\nimport \"strconv\"\n\n", pkg)
fmt.Fprintf(&b, "// String returns the constant name of r.\nfunc (r %s) String() string {\n\tswitch r {\n", *typeName)
for _, n := range names {
fmt.Fprintf(&b, "\tcase %s:\n\t\treturn %q\n", n, n)
}
fmt.Fprintf(&b, "\t}\n\treturn %q + strconv.Itoa(int(r)) + \")\"\n}\n", *typeName+"(")
src, err := format.Source(b.Bytes())
if err != nil {
log.Fatal(err)
}
if err := os.WriteFile(*out, src, 0o600); err != nil {
log.Fatal(err)
}
}// Package config loads settings with a fixed precedence: embedded defaults,
// then environment variables. The defaults travel inside the binary through
// //go:embed (Go 1.16+), so a scratch or distroless image needs no extra files.
package config
import (
_ "embed" // required for the //go:embed directive on a string or []byte
"encoding/json"
"fmt"
"strconv"
)
//go:embed default.json
var defaultJSON []byte
// Config is everything a binary needs to start.
type Config struct {
Addr string `json:"addr"`
Greeting string `json:"greeting"`
ShutdownSecs int `json:"shutdown_secs"`
}
// Load starts from the embedded defaults and applies overrides from lookup,
// which is os.LookupEnv in production and a map in tests.
func Load(lookup func(string) (string, bool)) (Config, error) {
var c Config
if err := json.Unmarshal(defaultJSON, &c); err != nil {
return Config{}, fmt.Errorf("embedded defaults: %w", err)
}
if v, ok := lookup("APP_ADDR"); ok && v != "" {
c.Addr = v
}
if v, ok := lookup("APP_GREETING"); ok && v != "" {
c.Greeting = v
}
if v, ok := lookup("APP_SHUTDOWN_SECS"); ok && v != "" {
n, err := strconv.Atoi(v)
if err != nil {
return Config{}, fmt.Errorf("APP_SHUTDOWN_SECS: %w", err)
}
c.ShutdownSecs = n
}
return c, nil
}// Package migrations embeds the SQL files that sit next to it, so the migration
// set is compiled into the binary and versioned together with the code. This is
// the //go:embed use case that most often replaces "copy the sql folder into
// the image".
package migrations
import (
"embed"
"io/fs"
"sort"
)
//go:embed *.sql
var files embed.FS
// Names returns the migration file names in the order they must be applied.
func Names() ([]string, error) {
entries, err := fs.ReadDir(files, ".")
if err != nil {
return nil, err
}
names := make([]string, 0, len(entries))
for _, e := range entries {
names = append(names, e.Name())
}
sort.Strings(names)
return names, nil
}
// Read returns the SQL text of one migration.
func Read(name string) (string, error) {
b, err := files.ReadFile(name)
if err != nil {
return "", err
}
return string(b), nil
}//go:build !debugmode
// Package debugmode shows build constraints: exactly one of on.go and off.go is
// compiled, chosen by `go build -tags debugmode`. The //go:build form replaced
// the older // +build comment in Go 1.17.
package debugmode
// Enabled reports whether the binary was built with -tags debugmode.
const Enabled = false1 go generate ./... runs: go run ../tools/genrole -type=Role ... (cwd = internal/role)
2 git diff --exit-code no change: the committed role_gen.go matches
3 go list -f '{{.EmbedFiles}}' ./internal/config [default.json]
4 go test ./internal/debugmode TestDisabledWithoutTag passes (asserts Enabled == false)
5 go test -tags debugmode ./internal/debugmode TestEnabledWithTag passes (asserts Enabled == true)
6 flip a constant in off.go go test fails: Enabled must be false when built without -tags debugmodeReal scenario: stringer, mockgen, protobuf and sqlc output kept current; SQL migrations and HTML templates inside the single binary; a debug build with extra endpoints; an integration test file behind //go:build integration.
| Feature | Directive | Runs at | Common pitfall |
|---|---|---|---|
| Generate | //go:generate | Only when you run go generate | Stale generated files |
| Embed | //go:embed | Compile time | Pattern outside the package; empty match is an error |
| Build tag | //go:build tag | Compile time | Forgetting the opposite file (!tag) |
tool directive | go.mod | go tool x | Needs Go 1.24+ |
Fix / how to use it: the Makefile's generate target runs both commands; use a blank _ "embed" import for []byte variables (the snippet does).
The go directive, toolchain directive and GOTOOLCHAIN Must-know
In plain words: go 1.24 in go.mod is the minimum Go your module needs, and since Go 1.21 the go command enforces it. toolchain go1.27.4 suggests a specific compiler. GOTOOLCHAIN decides whether the command may switch to another one.
Common misunderstanding: "The go line is advisory." Before Go 1.21 it was; now "the Go toolchain refuses to load a module or workspace that declares a minimum required Go version greater than the toolchain's own version". Also: "The go line sets the compiler version." It sets the minimum and the language version for that module's files.
Definition: the toolchain document: the go line "declares the minimum required Go version"; the toolchain line "declares a suggested toolchain"; with no toolchain line it is implied from the go line. A module's go line must be at least that of each module it requires. GOTOOLCHAIN is local, a name such as go1.21.0, auto (default, "shorthand for local+auto") or path, with <name>+auto forms. With auto a newer toolchain or go line makes the command download and run that toolchain. Go 1.25: updating the go line stops adding a toolchain line; Go 1.26: go mod init writes go 1.(N-2).0.
1 go 1.99 in go.mod, GOTOOLCHAIN=local go build
2 go: go.mod requires go >= 1.99 (running go 1.27.4; GOTOOLCHAIN=local)
3 GOTOOLCHAIN=auto GOPROXY=off go build
4 go: downloading go1.99.0 (darwin/arm64) -> toolchain not available
5 go get go@1.25.0 go: upgraded go 1.24.0 => 1.25.0Real scenario: a CI runner with Go 1.24 building a repository that says go 1.26, which silently downloads Go 1.26 (or fails offline); an air-gapped build that sets GOTOOLCHAIN=local to forbid downloads; a library keeping go 1.22 so older users can import it.
| Setting | Behaviour | When |
|---|---|---|
go 1.24 | Minimum for the module; language version | Library: lowest you really support |
toolchain go1.27.4 | Preferred compiler | Application: pin for reproducibility |
GOTOOLCHAIN=auto | May download newer | Developer laptops |
GOTOOLCHAIN=local | Never switch; error if too old | Air-gapped CI |
GOTOOLCHAIN=go1.27.4 | Exactly that one | Reproducible release builds |
//go:build go1.22 | Per-file language version bump | One file needing newer syntax |
Fix / how to use it: libraries pin low, applications pin both lines, CI uses actions/setup-go with go-version-file: go.mod so the version has one source of truth.
Dependencies: go mod vendor, go mod verify, GOFLAGS=-mod=vendor Important
In plain words: Your dependencies come from a module cache filled from a proxy and checked against go.sum. You can also copy them into a vendor/ directory so the build needs no network.
Common misunderstanding: "go mod verify checks go.sum." It checks that the module zips and extracted files in your cache "have not been modified since they were downloaded"; every normal command already checks go.sum hashes, and the checksum database covers first use.
Definition: go mod vendor creates vendor/ and vendor/modules.txt. Since go 1.14 in go.mod, a present and consistent vendor/ is used automatically (-mod=vendor: "the go command will not use the network or the module cache"); -mod=readonly (default otherwise) and -mod=mod ignore it. GOFLAGS=-mod=vendor forces it. If go.mod and vendor/modules.txt disagree the command stops (lab output: go: inconsistent vendoring in ..., saved in real-run-exp-C.txt). Output of go mod verify: all modules verified.
1 go mod download && go mod verify all modules verified
2 go mod vendor; cat vendor/modules.txt # golang.org/x/sync v0.19.0 / ## explicit; go 1.24.0
3 GOPROXY=off go build -o bin/ ./cmd/... exit 0 (vendor used automatically)
4 edit go.mod: x/sync v0.18.0 go: inconsistent vendoring in ...
5 empty GOMODCACHE, -mod=mod, GOPROXY=off module lookup disabled by GOPROXY=offReal scenario: an air-gapped build farm; a regulated shop that wants dependency code reviewed in the pull request; a team that wants builds to survive a proxy outage; CI that runs go mod verify after restoring a cache.
| Approach | Pros | Cons |
|---|---|---|
| Module cache + proxy | Small repo, fast | Needs the network or a mirror |
vendor/ committed | Hermetic, reviewable | Large diffs, repo growth |
GOFLAGS=-mod=mod | Updates go.mod on the fly | Surprising in CI; avoid |
go mod tidy in CI + diff | Catches drift | One more step |
Fix / how to use it: commit go.sum always; vendor only if you need hermetic builds; run go mod tidy and fail CI on a diff.
Vulnerability scanning with govulncheck Must-know
In plain words: govulncheck tells you which known vulnerabilities in your dependencies (and the standard library) your code can actually reach.
Common misunderstanding: "It lists every CVE in go.sum." It "reduces noise by prioritizing vulnerabilities in functions that your code is actually calling" (Go blog, v1.0.0, 13 July 2023). A vulnerable package that you import but never call is reported as informational.
Definition: govulncheck ./... analyses source; govulncheck -mode=binary bin/api analyses a compiled binary through its embedded build information. Install: go install golang.org/x/vuln/cmd/govulncheck@v1.1.4. It queries the Go vulnerability database (vuln.go.dev) and exits non-zero when it finds something. Lab output: No vulnerabilities found. for both modes.
1 govulncheck ./... source scan with call-graph analysis
2 govulncheck -mode=binary bin/api scan a built artefact (works on images' binaries)
3 Scanner: govulncheck@v1.1.4 DB: https://vuln.go.dev DB updated: 2026-11-24 15:56:00 UTC
4 No vulnerabilities found.Real scenario: a nightly CI job that fails when a new advisory hits a function you call; scanning the exact binary in the release image; upgrading the Go toolchain because the finding is in net/http.
| Mode | Input | Strength | Limit |
|---|---|---|---|
| source | Packages | Precise call analysis | Needs source and toolchain |
| binary | An executable | Scans what you ship | Less precise call info |
-show verbose | Either | More detail | Longer output |
Fix / how to use it: run it in CI on every merge and on a schedule; fix by upgrading the module or the Go version; see Secure SDLC & Incident Response for where scanning fits.
Reproducible builds Important
In plain words: The same source, the same toolchain and the same flags should give the same bytes anywhere. Then anyone can check that a published binary matches the source.
Common misunderstanding: "Go builds are always reproducible." They are close, but home-directory paths, the build time and VCS state leak in unless you prevent them. The Go team says "Go 1.21.0 is the first Go toolchain with perfectly reproducible builds" for the toolchains themselves.
Definition: inputs to pin: Go version (go and toolchain lines or GOTOOLCHAIN), dependencies (go.sum, or vendor/), GOOS/GOARCH, CGO_ENABLED=0, -trimpath, and -ldflags values that are functions of the commit (the commit time, not "now"). In the lab, the same commit built in two different directories gave different hashes without -trimpath and identical hashes with it (c2ed14d2... twice), and two make build runs in one directory matched (1698609e...).
1 r1/ and r2/ are copies of one commit
2 go build r1: 174dccb3... r2: 37ad566a... (different)
3 go build -trimpath r1: c2ed14d2... r2: c2ed14d2... (identical)
4 make build twice 1698609e... 1698609e... (identical)Real scenario: a supply-chain audit that rebuilds your tag and compares hashes; a cache that is keyed on binary hash; a security team that wants provenance.
| Source of difference | Fix |
|---|---|
| Absolute paths | -trimpath |
| Build date | Use the commit time, not date |
| Different Go patch version | Pin toolchain / GOTOOLCHAIN |
| cgo and C compiler version | CGO_ENABLED=0 |
| Dirty tree stamped by VCS | Build from a clean checkout or use -buildvcs=false |
| Different dependency versions | go.sum, go mod verify, vendoring |
Fix / how to use it: make "build twice, compare hashes" a CI check for release candidates.
Multi-stage Dockerfile: golang:1.27 → distroless or scratch Must-know
In plain words: The first stage has the compiler and builds the binary; the last stage contains only that binary. The image you run is small and has no shell to abuse.
Common misunderstanding: "FROM scratch works for any Go binary." It needs a static binary (CGO_ENABLED=0), and it has no CA certificates, no time zone data and no user database. Either copy those in, embed time/tzdata, or use distroless static which already ships them.
Definition: Docker's multi-stage doc: "With multi-stage builds, you use multiple FROM statements... Each FROM instruction can use a different base", and COPY --from=build copies results. The distroless README: "The smallest distroless image, gcr.io/distroless/static-debian13, is around 2 MiB", with nonroot tags. Cache: RUN --mount=type=cache,target=/go/pkg/mod keeps the module cache between builds; copy go.mod and go.sum first so the download layer survives source edits.
# syntax=docker/dockerfile:1
# ---- build stage: the full toolchain, never shipped ----
FROM golang:1.27 AS build
WORKDIR /src
# Copy only the module files first so this layer is cached until they change.
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod go mod download && go mod verify
COPY . .
ARG VERSION=dev
ARG COMMIT=unknown
ARG DATE=unknown
ARG PKG=academy/project-layout-linting-build/internal/version
# A static binary: no libc, so it runs on scratch and distroless/static.
RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 go build -trimpath \
-ldflags "-s -w -X ${PKG}.Version=${VERSION} -X ${PKG}.Commit=${COMMIT} -X ${PKG}.Date=${DATE}" \
-o /out/api ./cmd/api
# ---- runtime stage: only the binary ----
FROM gcr.io/distroless/static-debian13:nonroot
COPY --from=build /out/api /api
EXPOSE 8080
USER nonroot:nonroot
ENTRYPOINT ["/api"]1 docker build --build-arg VERSION=v1.4.0 -t academy/api:v1.4.0 . (expected, not run)
2 stage build: COPY go.mod go.sum; go mod download; COPY .; go build -> /out/api
3 stage runtime: FROM gcr.io/distroless/static-debian13:nonroot; COPY --from=build /out/api /api
4 docker run -p 8080:8080 academy/api:v1.4.0 -> listens as nonroot, no shellReal scenario: a 6 MB static binary on a 2 MiB base instead of a 900 MB builder image; a vulnerability scan that finds nothing to scan but one file; a rebuild after a one-line change that reuses the dependency layer.
| Runtime base | Size | Has shell | CA certs/tzdata | Use |
|---|---|---|---|---|
scratch | 0 | No | No | Smallest; you supply certs/tzdata |
distroless/static:nonroot | ~2 MiB | No | Yes | Default choice |
distroless/base | larger | No | Yes plus glibc | When cgo is needed |
alpine | ~7 MB | Yes (busybox) | Yes | Debugging convenience |
golang:1.27 | hundreds of MB | Yes | Yes | Build stage only |
Fix / how to use it: add a .dockerignore (.git, bin, vendor); pass VERSION, COMMIT, DATE as build args because .git is not in the context; run as non-root; see Containers & Kubernetes.
CI: GitHub Actions, setup-go and the build cache Must-know
In plain words: CI runs the same Makefile targets on every push. Caching the module and build caches turns a five-minute job into one.
Common misunderstanding: "I must configure caching by hand." actions/setup-go caches by default: "caching is enabled by default. To disable caching, set cache: false", and "by default, the cache key for Go modules is based on go.mod" (use cache-dependency-path: go.sum to key on go.sum).
Definition: go-version-file: go.mod makes the action read the go/toolchain lines ("Supports both go and toolchain directives"). golangci/golangci-lint-action runs the linter with a pinned version:. The snippet workflow has three jobs: test, lint, vuln.
# Copy to .github/workflows/ci.yml
name: ci
on:
push:
branches: [main]
tags: ["v*"]
pull_request:
permissions:
contents: read
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-go@v7
with:
go-version-file: go.mod # honours the go and toolchain lines
cache: true # module and build cache, keyed on go.sum
cache-dependency-path: go.sum
- run: go mod download && go mod verify
- run: go vet ./...
- run: go test -race -count=1 -coverprofile=cover.out ./...
- run: go build -trimpath ./cmd/...
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-go@v7
with:
go-version-file: go.mod
- uses: golangci/golangci-lint-action@v9
with:
version: v2.15
vuln:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-go@v7
with:
go-version-file: go.mod
- run: go install golang.org/x/vuln/cmd/govulncheck@v1.1.4
- run: govulncheck ./...1 push / pull_request / tag v* triggers
2 setup-go (go.mod, cache on) restores ~/go/pkg/mod and the build cache
3 go mod verify; go vet; go test -race; go build -trimpath ./cmd/...
4 golangci-lint-action version: v2.15
5 govulncheck ./...Real scenario: pull requests blocked on lint failures; a tag push building release binaries; a nightly scheduled govulncheck run.
| Concern | Setting |
|---|---|
| Go version | go-version-file: go.mod |
| Module cache | cache: true, cache-dependency-path: go.sum |
| Lint version | version: v2.15 (pin it) |
| Permissions | permissions: contents: read |
| Tags | on.push.tags: ["v*"] for releases |
Fix / how to use it: call make verify from one job if you want exact parity with local runs; keep the YAML thin.
Pre-commit hooks Good to know
In plain words: A pre-commit hook runs checks on your machine before a commit is created, so style failures never reach CI.
Common misunderstanding: "Hooks replace CI." Anyone can skip them (--no-verify) and they are not installed on a fresh clone until pre-commit install. CI stays the gate.
Definition: the pre-commit framework reads .pre-commit-config.yaml. golangci-lint publishes hooks: golangci-lint (changed files, with --fix), golangci-lint-full (whole module), golangci-lint-fmt and golangci-lint-config-verify. Note the upstream hook description: with changed-files mode "linters like 'unused' that need to scan all files won't work as expected".
# Copy to .pre-commit-config.yaml, then run: pre-commit install
repos:
- repo: https://github.com/golangci/golangci-lint
rev: v2.15.0
hooks:
- id: golangci-lint-config-verify # validates .golangci.yml
- id: golangci-lint-full # golangci-lint run --fix on the whole module
- id: golangci-lint-fmt # golangci-lint fmt
- repo: local
hooks:
- id: go-test
name: go test
entry: go test ./...
language: system
pass_filenames: false
types: [go]1 pre-commit install writes .git/hooks/pre-commit
2 git commit hooks run: config-verify, lint-full, fmt, go test
3 git commit --no-verify skips them (CI still catches)Real scenario: a formatter hook that stops "fix formatting" commits; a config-verify hook that stops a broken .golangci.yml from landing.
| Hook | Speed | Catches |
|---|---|---|
golangci-lint-fmt | Fast | Formatting |
golangci-lint-config-verify | Fast | Broken config |
golangci-lint-full | Slower | Everything the CI lint does |
local go test | Slowest | Regressions |
Fix / how to use it: keep hooks fast (format, config verify); leave slow checks to CI.
Semantic versioning and tags Important
In plain words: A release is a Git tag like v1.4.0. Go modules read tags as versions; users get a new minor or patch without surprises, and a breaking change needs a new major version in the import path.
Common misunderstanding: "Bumping to v2 is just a tag." For v2 and above the module path must end in /v2 (module github.com/acme/shop/v2) and every import changes. v0 and v1 carry no suffix. A v0.x module promises nothing.
Definition: semantic versioning (semver.org): MAJOR.MINOR.PATCH, a pre-release suffix (-rc.1) and build metadata (+meta). Go requires the v prefix. Nested modules are tagged with the directory prefix (api/v1.2.0). go install mod/cmd/x@v1.4.0 and go get mod@v1.4.0 resolve tags; @latest picks the highest release. A published version cannot be changed: the checksum database and proxy cache it, so a bad tag is retracted with a retract directive and a new version.
1 git tag -a v1.4.0 -m "v1.4.0" && git push origin v1.4.0
2 go get github.com/acme/shop@v1.4.0 resolved through the proxy
3 breaking change -> module github.com/acme/shop/v2, tag v2.0.0
4 bad release v1.4.1 -> add `retract v1.4.1` in go.mod, tag v1.4.2Real scenario: a library maintainer shipping a security fix as v1.4.1; a v2 migration where both majors coexist in one program; a CLI whose -version prints the tag.
| Change | Bump | Tag |
|---|---|---|
| Bug fix | PATCH | v1.4.1 |
| New backwards-compatible API | MINOR | v1.5.0 |
| Breaking API change | MAJOR and /v2 path | v2.0.0 |
| Pre-release | suffix | v1.5.0-rc.1 |
| Nested module | prefix | api/v1.2.0 |
Fix / how to use it: tag from a clean main, let CI build the tag, and let version stamping put the tag in the binary.
Mechanics
What go build does with your layout Important
In plain words: go build ./... walks the directories, treats every one with .go files as a package, builds dependencies first and caches each result by its inputs. Only package main directories produce an executable.
1 go list ./... every package in the module
2 directories without .go files skipped (docs/, deploy/, migrations/ with only .sql)
3 files with a false //go:build line excluded; a dir with none left is "build constraints exclude all Go files" only if named explicitly
4 testdata/ and names starting _ or . ignored by ./...
5 vendor/ (when active) dependencies read from it, no networkCommon misunderstanding: "./... includes everything under the directory." It skips directories named testdata, those starting with . or _, and nested modules (another go.mod starts another module).
| Variable / flag | Meaning |
|---|---|
GOFLAGS | Default flags for every go command (-mod=vendor, -trimpath) |
GOOS, GOARCH | Target platform |
CGO_ENABLED | 0 or 1 |
GOTOOLCHAIN | Toolchain selection |
GOPROXY, GOSUMDB, GOPRIVATE | Where modules come from and are verified |
GOWORK | Workspace file, off to disable |
GOBIN | Where go install writes |
GOMODCACHE | The module cache |
go.mod directives you will meet Important
| Directive | Meaning | Since |
|---|---|---|
module path | The module's import path | 1.11 |
go 1.24.0 | Minimum Go and language version | 1.11, enforced 1.21 |
toolchain go1.27.4 | Suggested toolchain | 1.21 |
require | Dependency versions (// indirect for transitive) | 1.11 |
replace | Substitute a module path or version | 1.11 |
exclude | Forbid a version | 1.11 |
retract | Mark your own versions as bad | 1.16 |
tool | Executable dependencies for go tool | 1.24 |
ignore | Directories the go command should ignore | 1.25 |
godebug | Default GODEBUG settings | 1.23 |
Exact error texts and exit codes Must-know
| Text (real unless marked) | Cause | Fix |
|---|---|---|
use of internal package academy/.../internal/version not allowed | Import from outside the parent tree | Move the code, or expose a public package |
package ... is not in std (...) | Import of a module you did not require | go get or add it to a go.work |
go: go.mod requires go >= 1.99 (running go 1.27.4; GOTOOLCHAIN=local) | The go line is newer than the toolchain | Upgrade Go or allow GOTOOLCHAIN=auto |
go: downloading go1.99.0 (darwin/arm64) then toolchain not available | Auto switch tried and failed | Check the version exists and the proxy is reachable |
go: inconsistent vendoring in ... | go.mod and vendor/modules.txt disagree | go mod vendor |
go: cannot write multiple packages to non-directory bin/api-vendor | -o file with several mains | -o bin/ |
module lookup disabled by GOPROXY=off | Dependency not in cache and no network | Fill the cache, or vendor |
all modules verified | go mod verify success | None |
File is not properly formatted (gofumpt) | A formatter would change the file | golangci-lint fmt |
golangci-lint run exit code 1 (default issues-exit-code) | Findings | Fix, or exclude with a reason |
The snippet module under test Good to know
// Package app is the HTTP application shared by every binary under cmd/. It
// lives in internal/ so that no other module can import it, which keeps its API
// free to change.
package app
import (
"fmt"
"net/http"
"academy/project-layout-linting-build/internal/config"
"academy/project-layout-linting-build/internal/version"
)
// Handler builds the routes. Dependencies come in as arguments, not globals.
func Handler(cfg config.Config, info version.Info) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
})
mux.HandleFunc("GET /version", func(w http.ResponseWriter, _ *http.Request) {
if _, err := fmt.Fprintln(w, info.String()); err != nil {
http.Error(w, "write failed", http.StatusInternalServerError)
}
})
mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, _ *http.Request) {
if _, err := fmt.Fprintf(w, "%s (%s)\n", cfg.Greeting, info.Version); err != nil {
http.Error(w, "write failed", http.StatusInternalServerError)
}
})
return mux
}package config
import "testing"
func lookupFrom(m map[string]string) func(string) (string, bool) {
return func(k string) (string, bool) { v, ok := m[k]; return v, ok }
}
func TestLoadDefaultsComeFromEmbed(t *testing.T) {
c, err := Load(lookupFrom(nil))
if err != nil {
t.Fatal(err)
}
if c.Addr != ":8080" || c.Greeting != "hello" || c.ShutdownSecs != 10 {
t.Fatalf("unexpected defaults: %+v", c)
}
}
func TestLoadEnvOverrides(t *testing.T) {
c, err := Load(lookupFrom(map[string]string{"APP_ADDR": ":9090", "APP_SHUTDOWN_SECS": "3"}))
if err != nil {
t.Fatal(err)
}
if c.Addr != ":9090" || c.ShutdownSecs != 3 || c.Greeting != "hello" {
t.Fatalf("override failed: %+v", c)
}
}
func TestLoadRejectsBadNumber(t *testing.T) {
if _, err := Load(lookupFrom(map[string]string{"APP_SHUTDOWN_SECS": "soon"})); err == nil {
t.Fatal("want an error for a non-numeric APP_SHUTDOWN_SECS")
}
}package migrations
import (
"strings"
"testing"
)
func TestNamesAreOrdered(t *testing.T) {
names, err := Names()
if err != nil {
t.Fatal(err)
}
if len(names) != 2 || names[0] != "0001_create_orders.sql" || names[1] != "0002_orders_customer_idx.sql" {
t.Fatalf("names = %v", names)
}
}
func TestReadReturnsEmbeddedSQL(t *testing.T) {
sql, err := Read("0001_create_orders.sql")
if err != nil {
t.Fatal(err)
}
if !strings.Contains(sql, "CREATE TABLE orders") {
t.Fatalf("unexpected content: %q", sql)
}
if _, err := Read("missing.sql"); err == nil {
t.Fatal("want an error for a file that was not embedded")
}
}-- internal/migrations/0001_create_orders.sql (embedded with //go:embed *.sql)
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer text NOT NULL,
total_cents bigint NOT NULL CHECK (total_cents >= 0),
created_at timestamptz NOT NULL DEFAULT now()
);
-- internal/migrations/0002_orders_customer_idx.sql
CREATE INDEX orders_customer_idx ON orders (customer, created_at DESC);Solving the classic problems
| Problem | Symptom | Solution | Cost |
|---|---|---|---|
| Everything in one package | 4,000-line files, slow reviews | Split by dependency (packages) | A few hours |
| Cyclic imports | import cycle not allowed | Move shared types to a domain package; adapters import it | Design work |
| Unknown version in production | "Which build is this?" | -X plus VCS fallback, /version | Minutes |
| Different binary on CI and laptop | Hash mismatch | -trimpath, CGO_ENABLED=0, pinned toolchain | Minutes |
| Lint noise on legacy code | 4,000 findings | new-from-rev, then ratchet | Setup day |
| Huge image | 900 MB | Multi-stage, distroless | Fifteen lines |
| Slow CI | 8-minute jobs | setup-go cache, -mod=vendor or proxy mirror | Minutes |
Sol 1: stale generated files
Add go generate ./... && git diff --exit-code to make generate and run it in CI; the snippet's role_gen.go is regenerated byte-identically (lab step 7).
Sol 2: a binary that will not start on scratch
Symptoms: exec /api: no such file or directory in a container. Cause: dynamic linking against glibc. Fix: CGO_ENABLED=0 and verify with file bin/api ("statically linked"). Missing HTTPS roots: copy /etc/ssl/certs/ca-certificates.crt from the build stage or use distroless.
Sol 3: adopting golangci-lint on a legacy repo
1 golangci-lint run --new-from-rev=origin/main ./... only new code is judged
2 fix findings in files you touch
3 later: remove new-from-rev, burn down with exclusions that name a ticketSol 4: a bad release
Add retract v1.4.1 // contains a data race to go.mod, tag v1.4.2; users of @latest skip the retracted version.
Sol 5: "which tool versions does CI use?"
Pin them: golangci-lint-action version: v2.15, govulncheck@v1.1.4, toolchain go1.27.4, or Go 1.24+ tool directives, then rebuild a tag twice and compare hashes.
Choosing
| Situation | Layout / tool choice | Extra technique | Reason |
|---|---|---|---|
| Weekend script | Flat, go.mod + main.go | go run . | Nothing to protect |
| Team service, one binary | cmd/api + internal/ | Makefile, golangci-lint standard + 6 | Testable run, private logic |
| Service + worker + migrator | cmd/* + shared internal/ | go build -o bin/ ./cmd/... | One module, one go.sum |
| Open-source library | Root package, internal/ for helpers | semver tags, retract when needed | Import path is the API |
| Library + CLI | Root + cmd/tool | go install .../cmd/tool@latest | Same module, both products |
| Many teams, many releases | Module per service, go.work locally | Prefix tags, GOWORK=off in CI | Independent versions |
| Air-gapped or regulated build | vendor/ + GOFLAGS=-mod=vendor | go mod verify, pinned toolchain | Hermetic and reviewable |
| Container delivery | Multi-stage, distroless static:nonroot | -trimpath, -X build args | Small, non-root, stamped |
| Cgo dependency unavoidable | distroless/base or debian-slim | CGO_ENABLED=1, same libc in build and run | Libc must match |
| Legacy repo adopting lint | new-from-rev | Ratchet | Stop new debt first |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One module, one binary. cmd/api/main.go builds the server; internal/ holds domain and adapters; a migrations/ directory is embedded into the binary so a deploy is "copy one file, run it". CI runs make verify; the release is git tag v1.4.0 and a make docker. Example: an orders service with internal/order, internal/postgres, internal/http, and a Dockerfile of fifteen lines. See A REST API in Go for a build of exactly this shape.
Modular monolith and multiple databases
Still one module and one binary, but internal/billing, internal/inventory and internal/search are packages with narrow exported APIs. Use nested internal/ (internal/billing/internal/ledger) to make a module's guts private to the module, and a linter such as depguard to forbid imports across modules (a rule file lists allowed packages). Each module owns its database schema directory; migrations are embedded per module. The layout enforces boundaries that process separation would otherwise enforce later.
Microservices
Two choices. One repository, one module, many cmd/*: shared internal/ code is easy, versions move together, the binaries are built in one go build -o bin/ ./cmd/.... Or one module per service with go.work for local work: independent versions and dependency graphs, and shared code must move into public packages of a library module ("the server repository grows packages that become useful for sharing... split these off to separate modules"). Each service gets its own image from the same Dockerfile pattern (ARG SERVICE), and CI builds only what changed. See Microservices project and Containers & Kubernetes.
Distributed data: replicas, caches, sharded databases, multi-region
Layout cannot fix distributed data, but build decisions reach it: a binary must run on amd64 and arm64 nodes (build both and publish a multi-arch image), migrations embedded in the binary must be compatible with the previous version while old pods still run (expand/contract), the version in /version tells you which replicas have rolled, and GOTOOLCHAIN plus the pinned image keep every region on the same compiler. A scan that finds a net/http advisory means rebuilding every region's image with a new Go, not editing configs.
Scaling path: 1×, 10×, 100×
| Scale | What changes | Layout and build practice |
|---|---|---|
| 1× (one developer) | Nothing hurts | Flat or cmd/ + internal/, go vet |
| 10× (a team, a few services) | Reviews and onboarding | golangci-lint pinned, Makefile, CI cache, Docker multi-stage, govulncheck |
| 100× (many teams, many repos) | Dependency and release coordination | Module per service, go.work locally, shared lint config repository, reproducible builds, SBOM and provenance, retract discipline |
Lab
All outputs below are real (Go 1.27.4, macOS arm64) except the Docker step.
1. Run the module's checks (real)
$ cd docs/snippets/go/project-layout-linting-build/go
$ gofmt -l . (no output)
$ go vet ./... (no output)
$ go test -race -count=1 ./...
ok academy/project-layout-linting-build/cmd/api
ok academy/project-layout-linting-build/cmd/worker
ok academy/project-layout-linting-build/internal/app
ok academy/project-layout-linting-build/internal/config
ok academy/project-layout-linting-build/internal/debugmode
ok academy/project-layout-linting-build/internal/migrations
ok academy/project-layout-linting-build/internal/role
ok academy/project-layout-linting-build/internal/version
ok academy/project-layout-linting-build/lintdemo/good2. Stamp, build and inspect (real)
$ git describe --tags --always --dirty
v1.4.0
$ make build && ./bin/api -version
v1.4.0 commit=9d9483e date=2026-11-28T11:27:30Z go1.27.4
$ go version -m bin/api
bin/api: go1.27.4
path academy/project-layout-linting-build/cmd/api
mod academy/project-layout-linting-build v1.4.0
build -trimpath=true
build CGO_ENABLED=0
build GOARCH=arm64
build GOOS=darwin
build vcs=git
build vcs.revision=9d9483e0745222556b9c10c31bb9f4d5f61dad85
build vcs.time=2026-11-28T11:27:30Z
build vcs.modified=false3. Reproducibility and cross-compilation (real)
without -trimpath: 174dccb3... (r1) 37ad566a... (r2) different
with -trimpath: c2ed14d2... (r1) c2ed14d2... (r2) identical
paths of the build directory inside the binary: 4 hits without, 0 with
$ file bin/api-linux-amd64 bin/api-linux-arm64 bin/api-darwin-arm64
ELF 64-bit LSB executable, x86-64, statically linked
ELF 64-bit LSB executable, ARM aarch64, statically linked
Mach-O 64-bit executable arm64
$ go build ./cmd/... exit 0, nothing written
$ go build -o bin/ ./cmd/... api worker4. Lint the bad twin (real)
$ golangci-lint run --build-tags lintdemo ./lintdemo/bad/...
(12 findings, listed in the linters section)
12 issues: errcheck 1, errorlint 1, exhaustive 1, gocritic 1, gosec 3,
govet 1, ineffassign 1, revive 2, unused 1
$ golangci-lint run ./... 0 issues.
$ staticcheck -tags lintdemo ./lintdemo/bad
bad.go:30:2: this value of n is never used (SA4006)
bad.go:60:21: Printf format %d has arg #1 of wrong type string (SA5009)
bad.go:63:6: func helperNobodyCalls is unused (U1000)5. Vendor, verify and scan (real)
$ go mod verify all modules verified
$ go mod vendor; cat vendor/modules.txt # golang.org/x/sync v0.19.0 / ## explicit; go 1.24.0
$ GOPROXY=off go build -o bin/ ./cmd/... exit 0
$ govulncheck ./... No vulnerabilities found.
$ govulncheck -mode=binary bin/api No vulnerabilities found.6. internal, workspaces and toolchains (real)
(module example.test/app imports academy/.../internal/version, both in a go.work)
package example.test/app
main.go:6:2: use of internal package academy/project-layout-linting-build/internal/version not allowed
$ GOTOOLCHAIN=local go build ./... (go.mod says go 1.99)
go: go.mod requires go >= 1.99 (running go 1.27.4; GOTOOLCHAIN=local)7. Generate and embed (real)
$ go generate ./... && git diff --exit-code -- internal/role/role_gen.go exit 0
$ go list -f '{{.EmbedFiles}}' ./internal/config [default.json]8. Docker build (expected, not run)
$ make docker VERSION=v1.4.0
# expected: stage build downloads modules once (cached), compiles /out/api,
# stage runtime is gcr.io/distroless/static-debian13:nonroot with one file /api
$ docker run --rm academy/api:v1.4.0 -version
# expected: v1.4.0 commit=<sha> date=<time> go1.27.xFor PHP/Laravel developers
A Laravel project has a fixed skeleton (app/, routes/, config/, database/migrations/), Composer's vendor/ and PSR-4 autoloading, so "where does a file go" is answered by the framework. Go has no framework skeleton: the module is the unit, go.mod plays the role of composer.json (versions live there), go.sum records integrity hashes rather than acting as a Composer-style lockfile, the module cache replaces vendor/ (which is optional), and the layout is yours. Tools map as follows: Laravel Pint ("an opinionated PHP code style fixer", with a --test mode that only inspects) to gofmt/goimports, a PHP static analyser to go vet and staticcheck, composer audit (a Composer command) to govulncheck, composer.json scripts to a Makefile, and Laravel Sail (the Docker development environment) to a Dockerfile plus Compose.
// composer.json "scripts": a task runner for PHP projects
// "scripts": { "lint": "pint --test", "test": "pest", "analyse": "phpstan analyse" }
// Go: the same job is a Makefile target that CI calls verbatim
// make lint -> golangci-lint run ./... && golangci-lint fmt --diff ./...| Laravel / PHP | Go |
|---|---|
app/, routes/, config/ fixed by the framework | cmd/, internal/ chosen by you |
composer.json + composer.lock | go.mod + go.sum |
vendor/ always present | Module cache by default; vendor/ optional |
| Pint | gofmt, goimports (golangci-lint fmt) |
| A PHP static analyser | go vet, staticcheck, golangci-lint |
composer audit | govulncheck |
php artisan commands | Several cmd/* binaries, or subcommands |
.env read at boot | Environment variables plus embedded defaults |
| Sail (Docker dev environment) | Multi-stage Dockerfile, one static binary on distroless |
Deploy by git pull + composer install | Copy or pull one artefact |
Common misconceptions
| Belief | Reality |
|---|---|
| Go has an official project layout | Only internal/ is enforced by the tool; the rest is convention |
| golang-standards/project-layout is the standard | Its README says it is not official; issue 117 criticises it |
pkg/ is required for public code | Most Go packages do not use it |
internal/ is only a convention | The go command rejects outside imports |
A workspace lifts internal/ | It does not; visibility follows import-path prefixes, so an unrelated module path is still refused |
go build ./cmd/... makes binaries | With several mains and no -o, nothing is written |
-ldflags -X sets any variable | Only string variables initialised to constants, with the full import path |
The go line is advisory | Enforced since Go 1.21; the toolchain may switch or refuse |
go mod verify checks go.sum | It checks the module cache against recorded hashes |
FROM scratch works for every binary | Needs a static binary, CA certificates and zone data |
go generate runs during go build | Never; commit generated files and diff in CI |
golangci-lint default: all is best | It adds noise and breaks on upgrades; use standard plus a short list |
| Builds are bit-for-bit reproducible by default | Needs -trimpath, a pinned toolchain, CGO_ENABLED=0, commit-derived stamps |
Cheat sheet
| Topic | Remember |
|---|---|
| Layout | Flat for small; cmd/<name> + internal/ for services; no pkg/ unless you export |
internal/ | Importable only from the parent tree; enforced by the compiler |
| Module path | go.mod at root, first line module host/org/repo; /v2 for major 2+ |
| Multi-module | go.work for local dev, GOWORK=off in CI, prefix tags |
| Lint config | version: "2"; default: standard + a short enable; config verify |
| Formatters | golangci-lint fmt; gofmt + goimports; gofumpt if the module path has a dot |
| Build | CGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X pkg.Version=$V" -o bin/ ./cmd/... |
| Cross-compile | GOOS, GOARCH; go tool dist list |
| Version | -X plus debug.ReadBuildInfo; go version -m bin/api |
| Toolchain | go is a minimum; toolchain a suggestion; GOTOOLCHAIN=local forbids downloads |
| Dependencies | go mod verify, go mod vendor, -mod=vendor; commit go.sum |
| Scan | govulncheck ./... and -mode=binary |
| Docker | Multi-stage, cache go.mod first, distroless/static:nonroot |
| CI | setup-go with go-version-file, cache on, pinned lint version |
| Releases | vMAJOR.MINOR.PATCH tags, retract for bad ones |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What does internal/ do, and who can import module/internal/x? Must-know
Answer
Answer: The go command allows an import of a path containing internal only from code rooted at the parent of that internal directory, so module/internal/x is importable by every package whose import path starts with module/ (even from a separate module with such a path) and by nobody else, including a module with an unrelated path in a go.work workspace. The error is use of internal package ... not allowed.
2 — Do you need pkg/ in a Go service? Must-know
Answer
Answer: No. The tool gives pkg/ no meaning, an application exports nothing, and most Go packages do not use it (Russ Cox, issue 117). Libraries put public packages at the root or in named directories and keep helpers in internal/.
3 — Is golang-standards/project-layout an official standard? Must-know
Answer
Answer: No. Its own README says it is not official and that its layout is overkill for small projects; issue 117 criticises the claim. The official guidance is "Organizing a Go module" on go.dev. Adopt folders only when you have the asset.
4 — Why keep main tiny and put logic behind a run function? Important
Answer
Answer: Calling main from a test is inconvenient and unsafe (it blocks, reads real arguments and may call os.Exit), while a test can call run(ctx, args, lookup, stdout) with fakes, test -version and graceful shutdown, and avoid globals. A separate runMain also lets deferred cleanup run before os.Exit (the gocritic exitAfterDefer finding).
5 — A teammate sets -ldflags "-X main.version=v1" and nothing changes. Why? Important
Answer
Answer: -X needs the full import path (academy/.../internal/version.Version, not main.version if the variable lives elsewhere) and a string variable that is uninitialised or set to a constant string expression; initialisers that call functions are ignored. A wrong path fails silently, so test with bin/api -version.
6 — What do -trimpath and CGO_ENABLED=0 buy you? Must-know
Answer
Answer: -trimpath removes build-directory paths so the same commit built in two directories gives identical bytes (lab: identical hashes) and stack traces do not leak local paths. CGO_ENABLED=0 gives a static binary that runs on scratch or distroless static.
7 — What is the difference between the go line and the toolchain line, and what does GOTOOLCHAIN=local do? Must-know
Answer
Answer: go is the minimum required version (enforced since Go 1.21), toolchain a suggested compiler. With GOTOOLCHAIN=auto the command may download a newer toolchain; with local it never switches and fails with go.mod requires go >= X (running go Y; GOTOOLCHAIN=local).
8 — How do you make golangci-lint adoptable in a large legacy repository? Important
Answer
Answer: Use issues.new-from-rev (or new-from-merge-base) so only new code is judged, start from default: standard plus a few linters, pin the version, and fix files as you touch them. Do not enable all.
9 — Why does go build ./cmd/... leave no files behind, and how do you fix it? Important
Answer
Answer: With several main packages and no -o, go build only compiles and discards. Use go build -o bin/ ./cmd/... (a directory) or go install ./cmd/.... -o file with several mains errors: cannot write multiple packages to non-directory.
10 — When would you use go mod vendor, and what does go mod verify check? Important
Answer
Answer: For hermetic or air-gapped builds and reviewable dependency code; with go 1.14+ a consistent vendor/ is used automatically (-mod=vendor, no network). go mod verify checks that modules in the module cache have not been modified since download; go.sum checking happens on every command.
11 — Why a multi-stage Dockerfile, and scratch or distroless? Must-know
Answer
Answer: The build stage has the compiler; the runtime stage contains only the static binary, so the image is small and has no shell or package manager. Distroless static:nonroot ships CA certificates and zone data and a non-root user; scratch has nothing, so you supply them.
12 — What does govulncheck add over a CVE list? Important
Answer
Answer: It uses the Go vulnerability database and call analysis to report vulnerabilities in functions your code actually calls, for source (./...) or a binary (-mode=binary), reducing noise. Run it in CI and on a schedule.
13 — How do you make a release build reproducible? Good to know
Answer
Answer: Pin the toolchain (go/toolchain lines or GOTOOLCHAIN), use go.sum or vendoring, CGO_ENABLED=0, -trimpath, stamp the commit time rather than "now", and build from a clean tree. Verify by building twice and comparing hashes.
Glossary
| Term | Meaning |
|---|---|
| Module | A tree of packages with one go.mod at its root |
| Package | A directory of .go files sharing a package name |
go.mod | Module file: module path, go, toolchain, require, replace, ... |
go.sum | Hashes of module contents used to verify downloads |
| Import path | Module path plus directory, used in import |
cmd/ | Directory holding one subdirectory per executable |
internal/ | Directory whose packages only the parent tree may import |
pkg/ | Optional directory for public packages; debated, not special |
| Flat layout | Project with files in the root and no sub-packages |
| Multi-module repo | Repository with several go.mod files |
go.work | Workspace file listing local modules to use together |
| Package naming | Short, lowercase, no underscores, no util |
| golang-standards/project-layout | Community repository of folder patterns, not official |
go vet | Standard analyser for suspicious constructs |
| staticcheck | External analyser with SA, S, ST, U checks |
| golangci-lint | Runner for many linters and formatters |
.golangci.yml | golangci-lint configuration; v2 starts with version: "2" |
default: standard | errcheck, govet, ineffassign, staticcheck, unused |
| errcheck | Finds ignored errors |
| revive | Style linter, successor of golint |
| gosec | Security linter, rule ids Gxxx |
| gocritic | Collection of diagnostics and style checks |
| exhaustive | Checks that enum switches name every constant |
| ineffassign | Finds assignments that are never read |
| unused | Finds unused identifiers |
| Formatter | Tool that rewrites source layout: gofmt, goimports, gofumpt, gci |
//nolint | Comment that suppresses a golangci-lint finding |
| Makefile | File of named command recipes run with make |
-ldflags | Flags passed to the linker |
-X | Linker flag that sets a string variable at link time |
-s -w | Strip symbol table and DWARF info |
-trimpath | Remove file system paths from the binary |
CGO_ENABLED | 0 disables cgo, giving static binaries |
GOOS / GOARCH | Target operating system and CPU architecture |
| Cross-compilation | Building for another platform than the host |
go install | Builds and installs executables into GOBIN |
go generate | Runs //go:generate commands on demand |
//go:embed | Compile-time inclusion of files in the binary |
//go:build | Build constraint line choosing files per tag |
| Build tag | A name enabled with -tags |
go directive | Minimum Go version and language version of a module |
toolchain directive | Suggested Go toolchain for the module |
GOTOOLCHAIN | Setting that selects or allows switching toolchains |
| Vendoring | Copying dependencies into vendor/ |
go mod verify | Checks the module cache against recorded hashes |
GOFLAGS | Environment variable with default flags for go commands |
buildvcs | Flag controlling VCS stamping into binaries |
go version -m | Prints the module and build info of a binary |
| govulncheck | Scanner for known vulnerabilities your code reaches |
| Reproducible build | Same inputs give identical bytes |
| Multi-stage build | Dockerfile with several FROM stages |
| distroless | Minimal runtime images without shell or package manager |
| scratch | The empty base image |
setup-go | GitHub Action that installs Go and caches modules |
| pre-commit | Framework that runs hooks before each commit |
| Semantic versioning | MAJOR.MINOR.PATCH scheme used in module tags |
retract | go.mod directive marking versions as bad |
References
- Go documentation, "Organizing a Go module": https://go.dev/doc/modules/layout
- Go documentation, "Managing dependencies": https://go.dev/doc/modules/managing-dependencies
- Go Modules Reference: https://go.dev/ref/mod
- Go Toolchains: https://go.dev/doc/toolchain
gocommand documentation: https://go.dev/cmd/go/linkcommand documentation: https://go.dev/cmd/link/- Go 1.4 release notes (internal packages): https://go.dev/doc/go1.4
- Go 1.11 release notes (modules): https://go.dev/doc/go1.11
- Go 1.13 release notes (
-trimpath): https://go.dev/doc/go1.13 - Go 1.14 release notes (vendoring): https://go.dev/doc/go1.14
- Go 1.16 release notes (embed, install): https://go.dev/doc/go1.16
- Go 1.17 release notes (
//go:build): https://go.dev/doc/go1.17 - Go 1.18 release notes (buildvcs, workspaces): https://go.dev/doc/go1.18
- Go 1.20 release notes (cgo default): https://go.dev/doc/go1.20
- Go 1.21 release notes (toolchains): https://go.dev/doc/go1.21
- Go 1.24 release notes (tool directive, version stamping): https://go.dev/doc/go1.24
- Go 1.25 release notes: https://go.dev/doc/go1.25
- Go 1.26 release notes: https://go.dev/doc/go1.26
- Go 1.27 release notes: https://go.dev/doc/go1.27
- "Perfectly Reproducible, Verified Go Toolchains": https://go.dev/blog/rebuild
- "Govulncheck v1.0.0 is released!": https://go.dev/blog/govulncheck
- Govulncheck tutorial: https://go.dev/doc/tutorial/govulncheck
- Workspaces tutorial: https://go.dev/doc/tutorial/workspaces
- Package names (Go blog): https://go.dev/blog/package-names
- Effective Go: https://go.dev/doc/effective_go
- golang-standards/project-layout README: https://raw.githubusercontent.com/golang-standards/project-layout/master/README.md
- golang-standards/project-layout issue 117: https://github.com/golang-standards/project-layout/issues/117
- Ben Johnson, "Standard Package Layout": https://www.gobeyond.dev/standard-package-layout/
- golangci-lint reference configuration: https://raw.githubusercontent.com/golangci/golangci-lint/main/.golangci.reference.yml
- golangci-lint configuration: https://golangci-lint.run/docs/configuration/
- golangci-lint linters: https://golangci-lint.run/docs/linters/
- golangci-lint formatters: https://golangci-lint.run/docs/formatters/
- golangci-lint migration guide: https://golangci-lint.run/docs/product/migration-guide/
- golangci-lint pre-commit hooks: https://raw.githubusercontent.com/golangci/golangci-lint/main/.pre-commit-hooks.yaml
- golangci-lint-action: https://raw.githubusercontent.com/golangci/golangci-lint-action/main/README.md
- staticcheck documentation: https://staticcheck.dev/docs/
- staticcheck checks: https://staticcheck.dev/docs/checks/
- actions/setup-go: https://raw.githubusercontent.com/actions/setup-go/main/README.md
- Docker multi-stage builds: https://docs.docker.com/build/building/multi-stage/
- Docker build cache optimisation: https://docs.docker.com/build/cache/optimize/
- Distroless images: https://raw.githubusercontent.com/GoogleContainerTools/distroless/main/README.md
- Semantic Versioning: https://semver.org/
- x/sync go.mod at v0.19.0: https://raw.githubusercontent.com/golang/sync/v0.19.0/go.mod
- x/sync go.mod at v0.20.0: https://raw.githubusercontent.com/golang/sync/v0.20.0/go.mod
- Composer CLI documentation: https://getcomposer.org/doc/03-cli.md
- Laravel 13, Pint: https://laravel.com/docs/13.x/pint
- Laravel 13, Sail: https://laravel.com/docs/13.x/sail
- pre-commit: https://pre-commit.com/
- Go release metadata: https://go.dev/dl/?mode=json