CLI Cheatsheet

Mental map

Create       go mod init
Dependencies go get / go mod tidy
Run          go run
Compile      go build
Install      go install
Format       go fmt
Analyse      go vet
Test         go test
Inspect      go list / go doc / go env
Generate     go generate
Clean        go clean
Profile      go tool pprof
Workspace    go work

The complete command list is available through:

go help

For a specific command:

go help <command>

Starting a project

CommandPurpose
go mod init <module>Create a new Go module
go mod tidyAdd missing dependencies and remove unused ones
go mod downloadDownload dependencies without building
go mod verifyCheck downloaded dependencies have not changed
go mod init github.com/ben/example
go mod tidy

A module is normally an entire project or repository. The command creates a go.mod file.


Running and building

CommandPurpose
go run .Compile and run the current package
go run main.goRun one specific file
go buildCompile the current package
go build ./...Build every package in the module
go build -o appBuild a binary with a chosen name
go installCompile and install the current program
go run .
go build -o myapp
./myapp

go run uses a temporary binary. go build creates a binary but does not install it. (Go Packages)


Testing

CommandPurpose
go testTest the current package
go test ./...Test all packages
go test -v ./...Show individual test results
go test -run TestNameRun matching tests
go test -count=1Disable cached test results
go test -race ./...Detect data races
go test -cover ./...Show test coverage
go test -coverprofile=cover.out ./...Save coverage data
go test -v -run TestWalk

Run one subtest:

go test -run 'TestWalk/structs'

Open an HTML coverage report:

go test -coverprofile=cover.out ./...
go tool cover -html=cover.out

Benchmarks

go test -bench=.
go test -bench=BenchmarkWalk
go test -bench=. -benchmem

benchmem includes allocation statistics.

Fuzz tests

go test -fuzz=FuzzName
go test -fuzz=FuzzName -fuzztime=30s

Formatting and checking

CommandPurpose
go fmt ./...Format all Go packages
gofmt -w .Format files directly
go vet ./...Find suspicious code and likely mistakes
go test ./...Compile, vet and test code
go fix ./...Update code using Go’s automatic fixes
go fmt ./...
go vet ./...
go test ./...

go vet does not prove that code is correct. It finds suspicious patterns, such as incorrect formatting arguments, broken struct tags and copied lock values. go test automatically runs a high-confidence subset of vet checks. (Go Packages)

Inspect available vet checks:

go tool vet help
go tool vet help printf

Dependencies

CommandPurpose
go get example.com/pkgAdd or update a dependency
go get example.com/pkg@v1.2.3Request a specific version
go get example.com/pkg@latestRequest the latest version
go get example.com/pkg@noneRemove a dependency
go list -m allList all modules in the dependency graph
go mod graphPrint the module dependency graph
go mod why <module>Explain why a dependency is required
go get github.com/google/uuid@latest
go mod tidy

Use go get for dependencies used by your module.

Use go install to install command-line tools:

go install golang.org/x/tools/cmd/stringer@latest

Modern Go separates installing executables from changing project dependencies. (Go)


Listing and inspecting

CommandPurpose
go listList the current package
go list ./...List every package
go list -m allList modules
go envShow Go environment settings
go versionShow the installed Go version
go doc <name>Read documentation in the terminal
go help <command>Read help for a Go command
go doc fmt.Println
go doc http.Server
go help test
go help modules

Useful environment checks:

go env GOPATH
go env GOMOD
go env GOWORK
go env GOOS
go env GOARCH

Change a persistent Go setting:

go env -w GOPROXY=https://proxy.golang.org,direct

Undo it:

go env -u GOPROXY

Installing tools

go install <module>/cmd/<tool>@<version>

Example:

go install golang.org/x/tools/cmd/goimports@latest

Installed binaries normally go into:

go env GOBIN

When GOBIN is empty, Go normally uses:

$(go env GOPATH)/bin

Code generation

Run all //go:generate directives:

go generate ./...

Example directive:

//go:generate stringer -type=Status

Then run:

go generate

go generate is not run automatically by go build or go test. (Go Packages)


Cleaning caches

CommandPurpose
go cleanRemove generated build files
go clean -cacheClear the build cache
go clean -testcacheClear cached test results
go clean -modcacheDelete all downloaded modules
go clean -fuzzcacheClear cached fuzzing results
go clean -testcache

Be careful with:

go clean -modcache

It deletes the entire module download cache, so dependencies must be downloaded again. (Go Packages)


Workspaces

Workspaces allow several local modules to be developed together.

go work init ./api ./shared

Add another module:

go work use ./worker

Synchronise workspace dependency versions:

go work sync

Inspect whether workspace mode is active:

go env GOWORK

A workspace creates a go.work file.


Cross-compilation

Build for Linux:

GOOS=linux GOARCH=amd64 go build

Build for Apple Silicon:

GOOS=darwin GOARCH=arm64 go build

Build for Windows:

GOOS=windows GOARCH=amd64 go build -o app.exe

Common values:

VariableExamples
GOOSlinux, windows, darwin
GOARCHamd64, arm64, 386

List supported combinations:

go tool dist list

Build flags

Show executed commands

go build -x

Print commands without running them

go build -n

Force a complete rebuild

go build -a

Include build tags

go build -tags integration
go test -tags integration ./...

Reduce binary size

go build -ldflags="-s -w"

Insert build information

go build -ldflags="-X 'main.version=1.2.3'"

The Go variable must exist:

package main

var version = "development"

Debugging and profiling tools

View compiler escape analysis

go build -gcflags="-m"

More detail:

go build -gcflags="-m=2"

This explains which values escape to the heap.

CPU profiling

go test -cpuprofile=cpu.out
go tool pprof cpu.out

Memory profiling

go test -memprofile=memory.out
go tool pprof memory.out

Open the browser interface:

go tool pprof -http=:8080 cpu.out

Inspect a binary

go tool nm ./myapp
go tool objdump ./myapp

Some lower-level tools are accessed through go tool, including pprof, cover, vet, compile and objdump. (Go)


Vendor dependencies

Create a local vendor directory:

go mod vendor

Build using vendored dependencies:

go build -mod=vendor

Check vendored packages:

go list -mod=vendor all

This is useful for controlled or offline builds.


Useful everyday sequence

New project

mkdir my-project
cd my-project

go mod init github.com/ben/my-project
go test ./...
go run .

Before committing

go fmt ./...
go vet ./...
go test -race ./...
go mod tidy

Diagnose strange cached tests

go clean -testcache
go test -count=1 -v ./...

Full basic health check

go mod tidy
go fmt ./...
go vet ./...
go test -race -cover ./...
go build ./...