Go Tools and Commands

Go comes with a comprehensive set of built-in tools that help with development, testing, debugging, and code analysis. Understanding these tools is essential for effective Go development. This tutorial covers the most important Go commands and tools.

Core Go Commands

go run

The go run command compiles and runs Go programs in a single step. It’s perfect for quick testing and scripting.

# Run a single file
go run main.go

# Run multiple files
go run file1.go file2.go

# Run all .go files in current directory
go run .

Common uses:

  • Quick testing of code snippets
  • Running simple scripts
  • Prototyping applications

go build

The go build command compiles Go source files into executable binaries.

# Build current package
go build

# Build with specific output name
go build -o myprogram

# Build for different platforms
go build -o program-linux-amd64
GOOS=windows GOARCH=amd64 go build -o program-windows-amd64.exe
GOOS=darwin GOARCH=arm64 go build -o program-mac-arm64

# Build with build tags
go build -tags="production"

Cross-compilation examples:

# Windows 64-bit
GOOS=windows GOARCH=amd64 go build

# Linux 32-bit
GOOS=linux GOARCH=386 go build

# macOS ARM64 (Apple Silicon)
GOOS=darwin GOARCH=arm64 go build

# Linux ARM (Raspberry Pi)
GOOS=linux GOARCH=arm go build

go install

The go install command compiles and installs packages to the Go binary directory.

# Install current package
go install

# Install a specific package
go install github.com/user/package

# Install with version
go install github.com/user/[email protected]

go mod

Go modules manage dependencies and versioning.

# Initialize a new module
go mod init example.com/myproject

# Download dependencies
go mod download

# Add missing dependencies and remove unused ones
go mod tidy

# Edit go.mod file
go mod edit -require=github.com/example/[email protected]

# Verify dependencies
go mod verify

# Show module graph
go mod graph

# Explain why a module is needed
go mod why github.com/example/package

Code Analysis Tools

go fmt

go fmt automatically formats Go source code according to standard conventions.

# Format current directory
go fmt

# Format specific files
go fmt file1.go file2.go

# Format recursively
go fmt ./...

# Check if files are formatted (no output if properly formatted)
go fmt -l .

Features:

  • Standard indentation (tabs)
  • Proper spacing
  • Consistent brace placement
  • Maximum line length considerations

go vet

go vet examines Go source code and reports suspicious constructs.

# Vet current package
go vet

# Vet with specific checks
go vet -printf

# Vet all packages
go vet ./...

Common issues detected:

  • Unused variables
  • Incorrect printf format strings
  • Unreachable code
  • Incorrect locking patterns
  • Race conditions in some cases

goimports

goimports extends go fmt by also managing import statements.

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

# Format and fix imports
goimports -w .

# Check what would change
goimports -d .

Features:

  • Adds missing imports
  • Removes unused imports
  • Groups imports (standard library, third-party, local)
  • Formats code like gofmt

Testing Tools

go test

go test runs tests and benchmarks.

# Run tests in current package
go test

# Run tests with verbose output
go test -v

# Run specific test
go test -run TestFunction

# Run tests in all packages
go test ./...

# Run benchmarks
go test -bench=.

# Run benchmarks with memory allocation info
go test -bench=. -benchmem

# Run race detection
go test -race

# Generate coverage report
go test -cover

# Generate HTML coverage report
go test -coverprofile=coverage.out
go tool cover -html=coverage.out -o coverage.html

Coverage options:

# Coverage for specific packages
go test -cover ./pkg1 ./pkg2

# Coverage with function detail
go test -cover -covermode=count

# Coverage excluding generated files
go test -cover -coverprofile=coverage.out -tags="!generated"

Test Helpers

# Install test coverage tools
go install github.com/axw/gocov/gocov@latest
go install github.com/AlekSi/gocov-xml@latest

# Generate XML coverage report
gocov convert coverage.out | gocov-xml > coverage.xml

Debugging and Profiling

go tool

The go tool command provides access to various Go tools.

# View assembly code
go tool compile -S main.go

# Debug compilation
go build -x

# Show build cache info
go env GOCACHE

Race Detection

# Run with race detection
go run -race main.go
go test -race

# Build with race detection
go build -race

Profiling

# CPU profiling
go test -cpuprofile=cpu.out
go tool pprof cpu.out

# Memory profiling
go test -memprofile=mem.out
go tool pprof mem.out

# Block profiling
go test -blockprofile=block.out
go tool pprof block.out

# Mutex profiling
go test -mutexprofile=mutex.out
go tool pprof mutex.out

Documentation Tools

go doc

go doc shows documentation for packages and symbols.

# Documentation for current package
go doc

# Documentation for specific function
go doc Printf

# Documentation for external package
go doc json.Marshal

# Show examples
go doc -all fmt.Printf

# Generate documentation server
go doc -http=:8080

godoc

godoc serves Go documentation locally.

# Install godoc
go install golang.org/x/tools/cmd/godoc@latest

# Serve documentation
godoc -http=:6060

# Open http://localhost:6060 to view documentation

Code Generation Tools

go generate

go generate runs code generation commands specified in source files.

//go:generate stringer -type=Pill
//go:generate go run gen.go
# Run generate directives
go generate

# Generate for specific files
go generate file.go

# Generate recursively
go generate ./...

Common generators:

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

# Generate string methods for constants
stringer -type=Status

# Install mock generator
go install github.com/golang/mock/mockgen@latest

# Generate mocks
mockgen -source=interface.go -destination=mock.go

Advanced Build Tools

Build Constraints (Build Tags)

// +build linux darwin

//go:build linux || darwin

package unixonly
# Build with specific tags
go build -tags="debug"

# Test with tags
go test -tags="integration"

# Exclude tags
go test -tags="!integration"

Build Flags

# Build with custom ldflags
go build -ldflags="-X main.version=1.2.3 -X main.buildTime=$(date -u +%Y%m%d.%H%M%S)"

# Strip debug information
go build -ldflags="-s -w"

# Build with CGO
CGO_ENABLED=1 go build

# Build without CGO
CGO_ENABLED=0 go build

Workspace and Environment

go env

go env displays Go environment information.

# Show all environment variables
go env

# Show specific variable
go env GOPATH
go env GOROOT
go env GOOS
go env GOARCH

# Show module information
go env GOMOD
go env GOPROXY

go version

# Show Go version
go version

# Show version with more details
go version -m /path/to/binary

Performance Analysis Tools

go tool pprof

go tool pprof analyzes performance profiles.

# Start pprof interactive session
go tool pprof cpu.out

# Common commands in pprof:
# top - show top functions
# list function_name - show source code
# web - generate web visualization
# pdf - generate PDF report

Benchmarking

func BenchmarkFunction(b *testing.B) {
    for i := 0; i < b.N; i++ {
        // code to benchmark
    }
}
# Run benchmarks
go test -bench=.

# Compare benchmarks
go test -bench=. -benchmem -count=3

# Benchmark with CPU profiling
go test -bench=. -cpuprofile=cpu.out

Integration with Editors

goimports in editors

Most Go editors can be configured to use goimports automatically:

VS Code settings.json:

{
    "go.formatTool": "goimports",
    "go.lintTool": "golangci-lint"
}

Vim with vim-go:

let g:go_fmt_command = "goimports"

Custom Tools and Scripts

Makefile Integration

.PHONY: build test clean

build:
	go build -o bin/app .

test:
	go test ./...

cover:
	go test -coverprofile=coverage.out ./...
	go tool cover -html=coverage.out -o coverage.html

clean:
	go clean
	rm -f bin/app coverage.out coverage.html

deps:
	go mod tidy
	go mod verify

Pre-commit Hooks

#!/bin/bash
# .git/hooks/pre-commit

# Format code
go fmt ./...

# Vet code
go vet ./...

# Run tests
go test ./...

Best Practices

  1. Use go fmt/goimports - Always format your code before committing
  2. Run go vet regularly - Catch potential bugs early
  3. Write tests - Use go test for unit testing
  4. Use modules - Manage dependencies with go mod
  5. Profile performance - Use pprof for performance analysis
  6. Cross-compile - Build for multiple platforms when needed
  7. Use build tags - Separate platform-specific or environment-specific code
  8. Automate with make - Use Makefiles for common tasks

Troubleshooting

Common Issues

Build fails due to missing dependencies:

go mod tidy
go mod download

Tests fail in CI but pass locally:

# Check environment differences
go env

# Run with race detection
go test -race

Slow builds:

# Use build cache
go build -a

# Check cache location
go env GOCACHE

Import issues:

# List dependencies
go list -m all

# Check module graph
go mod graph

External Resources:

Related Tutorials:

Last updated on