Build, Run & TestThe commands you type most often. All of them accept ./... to match every package in the current module.
go build ./...
Compiles every package in the module. Without -o it only type-checks and links — no binary is left behind.
Example
go build -o bin/app ./cmd/app
Watch out./... skips the vendor directory and nested modules (directories with their own go.mod).
go run .
Compiles into a temp directory and runs immediately — the daily driver for local development.
Example
go run ./cmd/app --config dev.yaml
Watch outKilling the go run process may leave the actual child binary running — always ship go build artifacts in production.
go test ./...
Runs all tests. Handy flags: -v verbose, -run to filter by regex, -race for the race detector, -cover for coverage.
Example
go test -race -run TestParse ./pkg/parser/...
go test -coverprofile=cover.out ./... && go tool cover -html=cover.out
Watch outTest results are cached; changing env vars or external files does NOT invalidate the cache — force a rerun with -count=1.
go vet ./...
The official static analyzer: printf mismatches, unreachable code, malformed struct tags, and more.
Example
go vet ./... && staticcheck ./...
Watch outvet only covers a small set of high-confidence checks; add staticcheck in CI for much broader coverage.
go install pkg@version
Installs a command into GOBIN (default ~/go/bin) — the standard way to manage global Go tools.
Example
go install golang.org/x/tools/cmd/goimports@latest
go install honnef.co/go/tools/cmd/staticcheck@2025.1
Watch outWith @version, go install ignores the go.mod in the current directory and builds in isolation; to add a project dependency use go get, not go install.
go clean -cache -modcache
Wipes the build cache and module download cache — the last resort when dependency changes seem to have no effect.
Example
go clean -cache
go clean -modcache # harsher: deletes every downloaded module
Watch out-modcache deletes every downloaded module; the next build re-downloads everything, so use it carefully on CI images.
Modules & DependenciesDay-to-day go.mod / go.sum operations. When debugging dependency issues, reach for go mod graph and go mod why first.
go mod init <path>
Initializes a module and writes go.mod. The module path is exactly what others will use to import you.
Example
go mod init github.com/yourname/project
Watch outPrivate repos still need a full host-based path (e.g. git.company.com/team/proj); a short made-up name makes the module unresolvable.
go mod tidy
Adds/removes go.mod entries to match real imports and completes go.sum — run it before every commit.
Example
go mod tidy
go mod tidy -compat=1.26 # stay compatible with an older version
Watch outOn "missing go.sum entry", run go mod download <module> first, then tidy again; tidy scans build tags for the current GOOS/GOARCH only — mind -compat for older toolchains.
go get pkg@version
Adds, upgrades or downgrades a dependency (edits go.mod only — installs no binaries).
Example
go get github.com/gin-gonic/gin@latest
go get github.com/sirupsen/logrus@v1.9.3 # same for downgrades
Watch outOmitting the version means @upgrade and may pull a cascade of indirect upgrades; pin an exact version for minimal diffs.
go list -m -u all
Lists all dependencies with available upgrades (a [v1.2.3] suffix means a newer version exists).
Example
go list -m -u all
go list -m -versions github.com/spf13/cobra # every version of one module
Watch out"all" includes indirect deps and gets long; filter to direct deps with go list -m -f '{{if not .Indirect}}{{.Path}}{{end}}' all.
go mod why <pkg>
Answers "who pulled this package in?" by showing the import chain from your main packages to it.
Example
go mod why golang.org/x/sys
go mod graph | grep jwt # the full dependency graph
Watch outwhy shows the chain from the main module's perspective; for raw version requirements between modules use go mod graph.
go mod download
Downloads dependencies into the local cache without compiling — use it to warm up CI caches.
Example
go mod download
go mod download github.com/gin-gonic/gin # download just this module
Watch outMost "missing go.sum entry" build failures are fixed by downloading the offending module explicitly.
go mod verify
Verifies that cached modules match the hashes recorded in go.sum — guards against a tampered cache.
Example
go mod verify
Watch outOnly "all modules verified" is a pass; any mismatch means the cache is untrustworthy — run go clean -modcache.
Formatting & Code Toolsgofmt handles layout; goimports additionally manages imports — see our blog post for the full comparison.
gofmt -l -w .
Formats source code: -l lists non-conforming files, -w rewrites in place, -d shows the diff without writing.
Example
gofmt -l . # CI check: any output means failure
gofmt -d main.go # preview what would change
gofmt -s -w . # also simplify the code
Watch outgofmt never adds/removes imports and does not reorder import groups — that is goimports territory, and their output can differ.
goimports -l -w .
= gofmt + automatic import addition/removal + grouping (stdlib first, then third-party).
Example
go install golang.org/x/tools/cmd/goimports@latest
goimports -local github.com/myorg -w . # own packages in their own group
Watch outWithout -local, your own organization's packages land in the third-party group; the first run on a large repo builds an index and is expectedly slow.
go doc <pkg>.<symbol>
Reads documentation in the terminal — packages, functions and types, no browser needed.
Example
go doc net/http.Server
go doc json.Marshal
go doc github.com/gin-gonic/gin@latest # pkg@version since Go 1.27
Watch outQuerying a third-party package that is not downloaded yet fails — run go mod download first or append @version.
go generate ./...
Scans for //go:generate directives and runs them (mocks, stringer, and other codegen).
Example
//go:generate stringer -type=Status
go generate ./...
Watch outgo generate is NOT part of the build — go build never triggers it. Commit generated files or run it in CI.
gofumpt -l -w .
A stricter third-party formatter (a superset of gofmt), popular for enforcing team-wide style.
Example
go install mvdan.cc/gofumpt@latest
gofumpt -extra -w .
Watch outgofumpt output is a stricter gofmt-compatible style; mixing both tools on one repo creates flip-flopping diffs.
staticcheck ./...
The de-facto deep static analyzer: bugs, performance, deprecated APIs and simplifications.
Example
go install honnef.co/go/tools/cmd/staticcheck@latest
staticcheck ./...
Watch outComplements go vet rather than replacing it: vet covers compiler-grade certainties, staticcheck covers broader practice.
Key Environment VariablesValues set via go env -w persist in the go env file and apply to every shell session.
GOPROXY
The module download proxy. A regional mirror is essential where proxy.golang.org is unreachable or slow.
Example
go env -w GOPROXY=https://goproxy.cn,direct
go env -w GOPROXY=https://goproxy.io,direct # another popular mirror
Watch outPut direct last: it means "fall back to the origin only after all proxies fail"; writing only direct disables proxies entirely.
GOPRIVATE
Glob patterns for private module prefixes; matching modules bypass the proxy and checksum database and fetch directly.
Example
go env -w GOPRIVATE=git.company.com/*,github.com/myorg/*
go env -w GONOPROXY=git.company.com/* # bypass the proxy only
Watch outGOPRIVATE is the default for both GONOPROXY and GONOSUMDB; set those two individually when you only want one behavior.
GOFLAGS
Default flags appended to every go command, e.g. a global -mod=mod or -race.
Example
go env -w GOFLAGS=-mod=mod
go env -u GOFLAGS # unset the setting
Watch outWith a vendor/ directory and go >= 1.14, -mod=vendor is automatic — that is usually why go get edits seem to have no effect.
GOPATH / GOMODCACHE / GOBIN
GOPATH is the workspace root; modules cache at $GOPATH/pkg/mod (GOMODCACHE); installed binaries land in GOBIN.
Example
go env GOPATH GOMODCACHE GOBIN
go env -w GOBIN=$HOME/bin # custom install location
Watch out"command not found" right after go install almost always means GOBIN is not on your PATH.
CGO_ENABLED
Toggles CGO. Set it to 0 for cross-compilation and fully static binaries.
Example
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o app ./cmd/app
Watch outWith CGO off, net DNS resolution and os/user lookups fall back to pure-Go implementations that behave slightly differently from glibc (and are usually more reliable in Alpine containers).
GO111MODULE (legacy)
The Go 1.11–1.22 module-mode switch; removed from the go command entirely in Go 1.23 — no need to set it anymore.
Example
go env GO111MODULE # on current versions: unknown go environment variable
Watch outDelete GO111MODULE=on from legacy CI scripts; if a script starts failing after a toolchain upgrade, this is why.
go.mod Directivesgo.mod has only a handful of directives; mastering replace and retract resolves 80% of dependency disputes.
module / go / toolchain
Module path, minimum language version, and the expected toolchain — the three header lines of go.mod.
Example
module github.com/you/proj
go 1.26
toolchain go1.27.1
Watch outSince Go 1.21 the go directive is a hard floor: an older toolchain refuses to build instead of "giving it a try".
require
Declares a dependency with its minimum version. The // indirect comment marks deps your code does not import directly.
Example
require (
github.com/gin-gonic/gin v1.10.0
golang.org/x/sys v0.24.0 // indirect
)
Watch outSince Go 1.27, go mod tidy consolidates scattered require blocks into the standard direct/indirect two-block layout — hand-splitting blocks is pointless.
replace
Substitutes a module with a local directory or fork — the standard way to debug deps or apply temporary patches.
Example
replace github.com/foo/bar => ../bar
replace github.com/foo/bar v1.2.3 => github.com/you/bar v1.2.4-fix
Watch outreplace only applies to the main module: when someone imports your library, the replace directives inside it are ignored.
exclude
Explicitly excludes a broken version; the go command treats it as non-existent.
Example
exclude github.com/foo/bar v1.2.3
Watch outexclude is main-module-only too; to withdraw versions of a published library use retract, not exclude.
retract
Lets a library author withdraw published versions (the antidote to a bad release); go get automatically avoids them.
Example
retract (
v1.2.0 // shipped an unfinished feature by mistake
v1.1.9 // security issue, please upgrade to v1.1.10
)
Watch outretract does not delete versions (they stay on the proxy and can still be requested explicitly); it only removes them from queries like @latest.
Cross-Compilation & ToolchainsGo cross-compiles without any target-platform toolchain — two environment variables are enough.
GOOS / GOARCH
Target OS and architecture — prefix go build with them to cross-compile.
Example
GOOS=linux GOARCH=amd64 go build -o app-linux-amd64 ./cmd/app
GOOS=linux GOARCH=arm64 go build -o app-linux-arm64 ./cmd/app
GOOS=windows GOARCH=amd64 go build -o app.exe ./cmd/app
GOOS=darwin GOARCH=arm64 go build -o app-darwin-arm64 ./cmd/app
Watch outDependencies that use CGO (e.g. sqlite3 drivers) fail to cross-compile without a target C toolchain — switch to pure-Go alternatives like modernc.org/sqlite.
go tool dist list
Lists every GOOS/GOARCH pair supported by your toolchain.
Example
go tool dist list
go tool dist list | grep linux
Watch outExotic pairs (e.g. linux/riscv64) need no extra installation — if it is listed, it compiles.
GOTOOLCHAIN
Toolchain selection policy: auto downloads and switches per go.mod (default); local uses only the installed version.
Example
go env GOTOOLCHAIN
go env -w GOTOOLCHAIN=local # never download a toolchain automatically
Watch outOn CI images prefer local with the right version preinstalled — otherwise builds download a toolchain on the spot, which is slow and can fail.
-trimpath -ldflags "-s -w"
The release-build trio: strips local paths, symbol table and DWARF info — typically 20–30% smaller binaries.
Example
go build -trimpath -ldflags="-s -w" -o bin/app ./cmd/app
Watch outAfter -s -w, panics still carry line numbers but source-level debugging with delve is gone — use it for release artifacts only.
go version / go env
Shows the active toolchain version and full environment — the first step of any environment debugging.
Example
go version
go env GOVERSION GOOS GOARCH GOPROXY
go env -json # machine-readable dump of every setting
Watch outgo env shows the effective value, which can come from the OS environment, the go env -w file, or built-in defaults.
No matching entry — try another keyword.
Go Toolchain Command Cheat Sheet
A full-text searchable cheat sheet for the Go toolchain, organized into the six groups you reach for most: build & test (go build / go test), modules & dependencies (go mod tidy / go get), formatting (gofmt / goimports), key environment variables (GOPROXY / GOPRIVATE), go.mod directives (require / replace / retract), and cross-compilation & toolchain management.
Every entry ships a copy-paste example plus a real-world pitfall — why the go test result cache makes "changed env var, same result" happen, why a vendor directory makes go get look broken, and why replace only works in the main module. Maintained against current Go releases; applies to Go 1.27.x.
Features
- Full-Text Search — The search box filters across commands, descriptions and pitfalls — type a keyword and jump straight to the entry.
- Six High-Frequency Groups — Build & test, dependencies, formatting, environment variables, go.mod directives and cross-compilation, each in its own section.
- Copy-Paste Examples — Every command comes with a working example, including a multi-platform cross-compilation matrix.
- Pitfalls Called Out — Each entry carries a "Watch out" note — the difference from ordinary documentation.
- Maintained Per Release — The applicable Go version and update date are shown; entries are reviewed after each Go release.
- Pure Static, No Signup — Content is baked into the page at build time — complete on first paint, no login, no ads, no tracking.
How to use
- Type a command or keyword (e.g. tidy, proxy, replace) into the search box to filter entries instantly.
- Or click a section tab to jump to a group: build / deps / formatting / env / go.mod / cross-compile.
- Copy the commands from the example blocks; the Watch-out note tells you when the result differs from expectations.
- Need to format HTML/CSS/JS/SQL online? Use the code formatter; for the gofmt vs goimports deep dive, see the blog.
FAQ
What is the difference between gofmt and goimports?
gofmt only handles layout (indentation, alignment, spacing) and never touches imports; goimports builds on gofmt by adding/removing imports and sorting them into stdlib and third-party groups. Their output on the same file can differ — standardize on goimports -l in CI. See the blog post for the full comparison with CI configuration examples.
How do I configure GOPROXY behind a restricted network?
Run go env -w GOPROXY=https://goproxy.cn,direct (or another reachable mirror). The trailing direct means "fall back to the origin only after all proxies fail" and must come last; combine it with GOPRIVATE=git.company.com/* for private repositories so they skip the proxy and checksum database.
What is the difference between go get and go install?
go get only edits the current project's go.mod (add/upgrade/downgrade a dependency) and installs no binaries; go install pkg@version installs a command into GOBIN and ignores the go.mod of the current directory. Use go get for project dependencies and go install for global tools.
Does cross-compiling require a target-platform toolchain?
No. GOOS=linux GOARCH=arm64 go build is all it takes, and go tool dist list shows every supported pair. The only exception is CGO-based dependencies (such as some sqlite drivers), which need a target C toolchain or a pure-Go replacement.
Do I still need to set GO111MODULE?
No. It was the module-mode switch of the Go 1.11–1.22 era and was removed from the go command entirely in Go 1.23 — setting it has no effect. Delete GO111MODULE=on from legacy CI scripts.
Related tools & reading