Logo
Published on

Mastering the Go Command - Complete Guide

Authors

Mastering the Go Command - Complete Guide

The go command is the Swiss Army knife of Go development. It's your gateway to building, testing, formatting, and managing Go programs. Understanding its capabilities is essential for efficient Go development. This guide covers everything from basic usage to advanced techniques used in enterprise environments.

Overview of the Go Command

The go command is a command-line tool that provides all necessary functionality for Go development:

# Basic syntax
go <command> [arguments]

# Get help
go help
go help <command>

Core Philosophy

  • Convention over Configuration: Minimal configuration required
  • Zero Dependencies: Self-contained toolchain
  • Fast Execution: Optimized for developer productivity
  • Cross-Platform: Works identically across operating systems

Essential Go Commands

go version

# Check Go version
go version
# Output: go version go1.21.5 linux/amd64

# Detailed version info
go version -m /path/to/binary

go env

# Show all environment variables
go env

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

# Set environment variable
go env -w GOPROXY=direct
go env -w GO111MODULE=on

# Unset environment variable
go env -u GOPROXY

Key Environment Variables:

GOROOT=/usr/local/go          # Go installation
GOPATH=/home/user/go          # Workspace (legacy)
GOOS=linux                    # Target OS
GOARCH=amd64                  # Target architecture
GO111MODULE=on                # Module mode
GOPROXY=proxy.golang.org      # Module proxy
GOSUMDB=sum.golang.org        # Checksum database

Building and Running

go run

Execute Go programs directly without creating binaries:

# Run single file
go run main.go

# Run multiple files
go run main.go utils.go

# Run with arguments
go run main.go arg1 arg2

# Run package
go run .
go run ./cmd/server

# Run with build flags
go run -ldflags="-X main.version=1.0.0" main.go

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

Advanced Usage:

# Set environment variables
GOOS=windows go run main.go

# Enable debugging
go run -gcflags="-N -l" main.go

# Verbose output
go run -x main.go

go build

Compile Go programs into executable binaries:

# Build current package
go build

# Build specific file
go build main.go

# Build with custom output name
go build -o myapp main.go

# Build for different OS/architecture
GOOS=linux GOARCH=amd64 go build
GOOS=windows GOARCH=amd64 go build -o app.exe

# Build all packages
go build ./...

Build Optimization:

# Reduce binary size
go build -ldflags="-s -w" main.go

# Static linking
CGO_ENABLED=0 go build -a -ldflags '-extldflags "-static"' .

# Debug build
go build -gcflags="-N -l" main.go

# Release build with version
go build -ldflags="-X main.Version=1.0.0 -X main.BuildTime=$(date)" main.go

go install

Compile and install packages:

# Install current package
go install

# Install specific package
go install github.com/user/package@latest
go install github.com/user/package@v1.2.3

# Install to specific location
GOBIN=/usr/local/bin go install

# Install all tools
go install ./cmd/...

Example: Installing Popular Tools

# Install golangci-lint
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest

# Install air (live reload)
go install github.com/cosmtrek/air@latest

# Install delve debugger
go install github.com/go-delve/delve/cmd/dlv@latest

Testing Commands

go test

Run tests and benchmarks:

# Run tests in current package
go test

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

# Verbose output
go test -v

# Run specific test
go test -run TestFunctionName
go test -run "TestUser.*"

# Run tests with coverage
go test -cover
go test -coverprofile=coverage.out

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

# Run benchmarks
go test -bench=.
go test -bench=BenchmarkFunction

# Race detection
go test -race

# Short tests only
go test -short

# Parallel execution
go test -parallel 4

Advanced Testing:

# Test with build tags
go test -tags=integration

# Memory profiling
go test -memprofile=mem.prof

# CPU profiling
go test -cpuprofile=cpu.prof

# Timeout
go test -timeout=30s

# Fail fast
go test -failfast

# JSON output
go test -json

Test Example Project Structure

project/
├── main.go
├── main_test.go
├── internal/
│   ├── user/
│   │   ├── user.go
│   │   └── user_test.go
│   └── auth/
│       ├── auth.go
│       └── auth_test.go
└── integration/
    └── api_test.go

Module Management

go mod

Manage Go modules and dependencies:

# Initialize new module
go mod init github.com/user/project

# Add dependencies
go get github.com/gorilla/mux
go get github.com/gorilla/mux@v1.8.0

# Add development dependencies
go get -t github.com/stretchr/testify

# Update dependencies
go get -u
go get -u ./...

# Remove unused dependencies
go mod tidy

# Download dependencies
go mod download

# Verify dependencies
go mod verify

# Show module graph
go mod graph

# Show why dependency is needed
go mod why github.com/gorilla/mux

# Edit go.mod
go mod edit -require=github.com/user/package@v1.0.0
go mod edit -exclude=github.com/bad/package@v1.0.0
go mod edit -replace=github.com/old/package=github.com/new/package@v1.0.0

Module Commands in Practice:

# Create new project
mkdir myproject && cd myproject
go mod init github.com/username/myproject

# Add dependencies
go get github.com/gin-gonic/gin
go get github.com/lib/pq

# Update to latest
go get -u github.com/gin-gonic/gin

# Clean up
go mod tidy

# Vendor dependencies (optional)
go mod vendor

go.mod File Structure

module github.com/username/myproject

go 1.21

require (
    github.com/gin-gonic/gin v1.9.1
    github.com/lib/pq v1.10.9
)

require (
    github.com/bytedance/sonic v1.9.1 // indirect
    github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
    // ... more indirect dependencies
)

exclude github.com/bad/package v1.0.0

replace github.com/old/package => github.com/new/package v1.0.0

retract v1.0.1 // Published accidentally

Code Quality and Formatting

go fmt

Format Go source code:

# Format current directory
go fmt

# Format specific file
go fmt main.go

# Format all packages
go fmt ./...

# Show differences without formatting
gofmt -d .

# Format and write
gofmt -w .

go vet

Static analysis tool:

# Vet current package
go vet

# Vet all packages
go vet ./...

# Specific checks
go vet -printf=false ./...
go vet -structtag=false ./...

# Show all available analyzers
go tool vet help

Common Issues go vet Catches:

  • Printf format string mismatches
  • Unreachable code
  • Suspicious constructs
  • Struct tag validation
  • Assignment to nil maps

goimports

Manage imports automatically:

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

# Format and fix imports
goimports -w .

# Show differences
goimports -d .

Documentation

go doc

View documentation:

# Package documentation
go doc fmt
go doc net/http

# Function documentation
go doc fmt.Printf
go doc net/http.ListenAndServe

# Method documentation
go doc json.Decoder.Decode

# Show all exported items
go doc -all fmt

# Show source code
go doc -src fmt.Printf

godoc

Generate and serve documentation:

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

# Serve documentation locally
godoc -http=:6060

# Generate static documentation
godoc -html fmt > fmt.html

Advanced Commands

go list

List packages and modules:

# List current package
go list

# List all packages
go list ./...

# List with templates
go list -f '{{.ImportPath}} {{.Dir}}' ./...

# List dependencies
go list -deps

# List test files
go list -f '{{.TestGoFiles}}' ./...

# List modules
go list -m all
go list -m -versions github.com/gorilla/mux

# JSON output
go list -json

go work

Workspace management (Go 1.18+):

# Initialize workspace
go work init ./module1 ./module2

# Add module to workspace
go work use ./module3

# Edit workspace
go work edit -use=./module4

# Sync workspace
go work sync

Workspace Example:

workspace/
├── go.work
├── service-a/
│   ├── go.mod
│   └── main.go
├── service-b/
│   ├── go.mod
│   └── main.go
└── shared/
    ├── go.mod
    └── utils.go

go generate

Run code generation tools:

# Generate code
go generate

# Generate for all packages
go generate ./...

# Verbose output
go generate -v

Example generation directive:

//go:generate stringer -type=Status
//go:generate mockgen -source=interface.go -destination=mock.go

type Status int

const (
    Pending Status = iota
    Running
    Complete
)

Performance and Profiling

go tool pprof

Performance profiling:

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

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

# Web interface
go tool pprof -http=:8080 cpu.prof

# Top functions
go tool pprof -top cpu.prof

# List source code
go tool pprof -list=main.* cpu.prof

go tool trace

Execution tracing:

# Generate trace
go test -trace=trace.out

# View trace
go tool trace trace.out

go tool compile

Compiler tools:

# Escape analysis
go build -gcflags="-m" main.go

# Assembly output
go tool compile -S main.go

# Optimization levels
go build -gcflags="-l" main.go    # Disable inlining
go build -gcflags="-N" main.go    # Disable optimizations

Build Constraints and Tags

Build Tags

//go:build linux
// +build linux

package main

// This file only builds on Linux
# Build with tags
go build -tags="debug,integration"

# List build constraints
go list -f '{{.GoFiles}} {{.TestGoFiles}}' -tags=debug

Common Build Tags

//go:build !windows
//go:build linux || darwin
//go:build cgo
//go:build debug
//go:build integration

Enterprise Use Cases

CI/CD Pipeline Script

#!/bin/bash
set -e

# Linting
echo "Running linters..."
golangci-lint run

# Testing
echo "Running tests..."
go test -race -coverprofile=coverage.out ./...

# Coverage check
coverage=$(go tool cover -func=coverage.out | tail -1 | awk '{print $3}' | sed 's/%//')
if (( $(echo "$coverage < 80" | bc -l) )); then
    echo "Coverage $coverage% is below 80%"
    exit 1
fi

# Security scan
echo "Running security scan..."
gosec ./...

# Build
echo "Building application..."
go build -ldflags="-s -w -X main.Version=$VERSION" -o app

echo "Build successful!"

Makefile for Go Projects

.PHONY: build test clean lint cover deps

# Build configuration
APP_NAME := myapp
VERSION := $(shell git describe --tags --always --dirty)
BUILD_TIME := $(shell date -u '+%Y-%m-%d_%H:%M:%S')
LDFLAGS := -s -w -X main.Version=$(VERSION) -X main.BuildTime=$(BUILD_TIME)

# Build targets
build:
	go build -ldflags="$(LDFLAGS)" -o bin/$(APP_NAME) ./cmd/$(APP_NAME)

build-all:
	GOOS=linux GOARCH=amd64 go build -ldflags="$(LDFLAGS)" -o bin/$(APP_NAME)-linux-amd64 ./cmd/$(APP_NAME)
	GOOS=windows GOARCH=amd64 go build -ldflags="$(LDFLAGS)" -o bin/$(APP_NAME)-windows-amd64.exe ./cmd/$(APP_NAME)
	GOOS=darwin GOARCH=amd64 go build -ldflags="$(LDFLAGS)" -o bin/$(APP_NAME)-darwin-amd64 ./cmd/$(APP_NAME)

# Testing
test:
	go test -v -race ./...

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

bench:
	go test -bench=. -benchmem ./...

# Code quality
lint:
	golangci-lint run

fmt:
	gofmt -s -w .
	goimports -w .

vet:
	go vet ./...

# Dependencies
deps:
	go mod download
	go mod tidy

deps-update:
	go get -u ./...
	go mod tidy

# Utilities
clean:
	rm -rf bin/
	rm -f coverage.out coverage.html

install:
	go install ./cmd/$(APP_NAME)

run:
	go run ./cmd/$(APP_NAME)

Troubleshooting Common Issues

Module Issues

# Clear module cache
go clean -modcache

# Force re-download
go mod download -x

# Fix go.sum mismatches
go mod tidy

Build Issues

# Clean build cache
go clean -cache

# Rebuild everything
go build -a ./...

# Debug build process
go build -x ./...

Import Issues

# Fix imports
goimports -w .

# Check import paths
go list -f '{{.ImportPath}} -> {{.Dir}}' ./...

Performance Tips

Build Performance

# Parallel builds
GOMAXPROCS=8 go build ./...

# Use build cache
export GOCACHE=/tmp/go-cache

# Disable CGO for faster builds
CGO_ENABLED=0 go build

Test Performance

# Parallel testing
go test -parallel 8 ./...

# Cache test results
go test -cache ./...

# Short tests in development
go test -short ./...