Skip to content

Go Command Line Tools

Go language provides a rich set of command-line tools that are the core of the Go development process. Mastering these tools is essential for Go developers. This chapter will detail the various commands of the Go toolchain and their usage.

🔧 Go Toolchain Overview

Core Commands

bash
go help          # View help information
go version       # View version information
go env           # View environment variables
go build         # Compile packages
go run           # Compile and run programs
go install       # Compile and install packages
go clean         # Clean compiled files
go test          # Run tests
go fmt           # Format code
go vet           # Static analysis tool
go mod           # Module management
go get           # Download dependency packages
go list          # List package information
go doc           # View documentation
go generate      # Run generators

📖 Basic Command Details

1. go help - Help Information

View All Commands

bash
go help

View Specific Command Help

bash
go help build    # View build command help
go help run      # View run command help
go help mod      # View mod command help

Output Example

Go is a tool for managing Go source code.

Usage:
    go <command> [arguments]

The commands are:
    bug         start a bug report
    build       compile packages and dependencies
    clean       remove object files and cached files
    doc         show documentation for package or symbol
    env         print Go environment information
    fix         update packages to use new APIs
    fmt         gofmt (reformat) package sources
    generate    generate Go files by processing source
    get         add dependencies to current module and install them
    install     compile and install packages and dependencies
    list        list packages or modules
    mod         module maintenance
    work        workspace maintenance
    run         compile and run Go program
    test        test packages
    tool        run specified go tool
    version     print Go version
    vet         report likely mistakes in packages

2. go version - Version Information

Basic Usage

bash
# View Go version
go version
# Output: go version go1.21.0 darwin/amd64

# View detailed version information
go version -m /path/to/binary

Version Information Format

go version go1.21.0 darwin/amd64
           │        │      │
           │        │      └─ Architecture (amd64/arm64/386)
           │        └─ Operating System (linux/darwin/windows)
           └─ Go version number

3. go env - Environment Variables

View All Environment Variables

bash
go env

View Specific Environment Variables

bash
go env GOPATH GOROOT GOPROXY

Set Environment Variables

bash
# Set proxy
go env -w GOPROXY=https://goproxy.cn,direct

# Set private modules
go env -w GOPRIVATE=*.corp.example.com

# Reset environment variable
go env -u GOPROXY

Important Environment Variables

VariableDescriptionExample Value
GOROOTGo installation directory/usr/local/go
GOPATHWorkspace directory/home/user/go
GOBINExecutable installation directory$GOPATH/bin
GOOSTarget operating systemlinux, windows, darwin
GOARCHTarget architectureamd64, arm64, 386
GOPROXYModule proxy serverhttps://proxy.golang.org
GOSUMDBChecksum databasesum.golang.org

🔨 Compilation Commands

1. go build - Compile Packages

Basic Usage

bash
# Compile current directory
go build

# Compile specified file
go build main.go

# Compile specified package
go build ./cmd/app

# Compile all sub-packages
go build ./...

Common Options

bash
# Specify output filename
go build -o myapp main.go

# Cross-compilation
GOOS=linux GOARCH=amd64 go build -o myapp-linux

# Show compilation process
go build -v

# Pass linker flags during compilation
go build -ldflags "-X main.version=1.0.0"

# Disable optimization and inlining
go build -gcflags "-N -l"

Build Tags

go
// +build linux darwin
// Compile only on Linux and macOS

// +build !windows
// Compile on all systems except Windows

2. go run - Compile and Run

Basic Usage

bash
# Run single file
go run main.go

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

# Run package
go run .

# Pass arguments
go run main.go arg1 arg2

Example Code

go
// main.go
package main

import (
    "fmt"
    "os"
)

func main() {
    fmt.Println("Program name:", os.Args[0])
    fmt.Println("Argument list:", os.Args[1:])
}
bash
# Run and pass arguments
go run main.go hello world
# Output:
# Program name: /tmp/go-build123/b001/exe/main
# Argument list: [hello world]

3. go install - Compile and Install

Basic Usage

bash
# Install current package
go install

# Install specified package
go install github.com/user/package@latest

# Install to specified directory
GOBIN=/usr/local/bin go install

Difference from go build

CommandCompileInstall to GOBINGenerate Local File
go build
go install

🧹 Cleanup Commands

1. go clean - Clean Files

Basic Usage

bash
# Clean current package build cache
go clean

# Clean all package build cache
go clean -cache

# Clean module download cache
go clean -modcache

# Clean test cache
go clean -testcache

# Show files to be deleted without actually deleting
go clean -n

Cleanup Options Description

OptionDescriptionCleanup Content
-cacheClean build cache$GOCACHE directory
-modcacheClean module cache$GOPATH/pkg/mod
-testcacheClean test cacheTest result cache
-fuzzcacheClean fuzz testing cacheFuzz testing cache

📦 Package Management Commands

1. go mod - Module Management

Initialize Module

bash
# Initialize new module
go mod init module-name

# Example
go mod init github.com/username/project

Module Maintenance

bash
# Download dependencies
go mod download

# Add missing modules, remove unused modules
go mod tidy

# View dependency graph
go mod graph

# Explain why a module is needed
go mod why golang.org/x/crypto

# Verify dependencies
go mod verify

# Copy dependencies to vendor directory
go mod vendor

go.mod File Example

go
module github.com/example/project

go 1.21

require (
    github.com/gin-gonic/gin v1.9.1
    github.com/stretchr/testify v1.8.4
)

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

exclude github.com/example/bad-package v1.0.0

replace github.com/example/fork => ../local-fork

2. go get - Get Dependencies

Basic Usage

bash
# Get latest version
go get github.com/gin-gonic/gin

# Get specific version
go get github.com/gin-gonic/gin@v1.9.1

# Get specific commit
go get github.com/gin-gonic/gin@abc123

# Get latest pre-release version
go get github.com/gin-gonic/gin@latest

# Upgrade all dependencies
go get -u ./...

# Only upgrade patch versions (security updates)
go get -u=patch ./...

Version Selection Syntax

SyntaxDescriptionExample
@latestLatest versiongo get pkg@latest
@v1.2.3Specific versiongo get pkg@v1.2.3
@commitSpecific commitgo get pkg@abc123
@masterSpecific branchgo get pkg@master
@>=v1.2.0Version constraintgo get pkg@>=v1.2.0

🧪 Testing Commands

1. go test - Run Tests

Basic Usage

bash
# Run current package tests
go test

# Run all package tests
go test ./...

# Run specified package tests
go test ./pkg/utils

# Show detailed information
go test -v

Test Options

bash
# Run benchmark tests
go test -bench=.

# Generate coverage report
go test -cover

# Generate coverage file
go test -coverprofile=coverage.out

# View coverage details
go tool cover -html=coverage.out

# Run specific test function
go test -run TestFunctionName

# Set timeout
go test -timeout 30s

Example Test File

go
// math_test.go
package main

import "testing"

func TestAdd(t *testing.T) {
    result := Add(2, 3)
    expected := 5
    if result != expected {
        t.Errorf("Add(2, 3) = %d; want %d", result, expected)
    }
}

func BenchmarkAdd(b *testing.B) {
    for i := 0; i < b.N; i++ {
        Add(2, 3)
    }
}

🎨 Code Quality Tools

1. go fmt - Code Formatting

Basic Usage

bash
# Format current directory
go fmt

# Format specified file
go fmt main.go

# Format all packages
go fmt ./...

# View formatting differences without modifying
gofmt -d main.go

# Rewrite import paths
gofmt -w -r 'old -> new' *.go

2. go vet - Static Analysis

Basic Usage

bash
# Check current package
go vet

# Check all packages
go vet ./...

# Check specified package
go vet ./pkg/utils

Common Checks

  • Unused variables
  • Unreachable code
  • Printf format string errors
  • Method signature errors
  • Struct tag format errors

3. go generate - Code Generation

Basic Usage

bash
# Run generators for current package
go generate

# Run generators for all packages
go generate ./...

Generator Directive Example

go
// main.go
package main

//go:generate stringer -type=Status
type Status int

const (
    Pending Status = iota
    Running
    Completed
)

📚 Documentation Commands

1. go doc - View Documentation

Basic Usage

bash
# View package documentation
go doc fmt

# View function documentation
go doc fmt.Println

# View type documentation
go doc http.Server

# Show all exported identifiers
go doc -all fmt

# Show source code
go doc -src fmt.Println

2. godoc - Documentation Server

Start Local Documentation Server

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

# Start documentation server
godoc -http=:6060

# Access in browser
# http://localhost:6060

🔧 Other Useful Commands

1. go list - List Package Information

Basic Usage

bash
# List packages in current module
go list ./...

# List all dependencies
go list -m all

# Show detailed package information
go list -json .

# Find package import path
go list -find github.com/gin-gonic/gin

2. go tool - Toolchain

View Available Tools

bash
go tool

Common Tools

bash
# View assembly code
go tool objdump binary

# View symbol table
go tool nm binary

# Performance analysis
go tool pprof cpu.prof

# Code coverage
go tool cover -html=coverage.out

🎯 Practical Example

Create Complete Project Workflow

bash
# 1. Create project directory
mkdir myproject && cd myproject

# 2. Initialize module
go mod init github.com/username/myproject

# 3. Create main program
cat > main.go << 'EOF'
package main

import "fmt"

func main() {
    fmt.Println("Hello, Go!")
}
EOF

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

# 5. Create test file
cat > main_test.go << 'EOF'
package main

import "testing"

func TestMain(t *testing.T) {
    // Test code
}
EOF

# 6. Run tests
go test

# 7. Format code
go fmt

# 8. Static analysis
go vet

# 9. Build program
go build

# 10. Clean cache
go clean -cache

📋 Command Quick Reference

Daily Development Commands

CommandPurposeExample
go runQuick rungo run main.go
go buildCompile programgo build -o app
go testRun testsgo test -v ./...
go fmtFormat codego fmt ./...
go vetStatic checkgo vet ./...

Module Management Commands

CommandPurposeExample
go mod initInitialize modulego mod init myapp
go mod tidyTidy dependenciesgo mod tidy
go getAdd dependenciesgo get package@latest
go mod downloadDownload dependenciesgo mod download

Information Query Commands

CommandPurposeExample
go versionView versiongo version
go envView environmentgo env GOPATH
go listList package infogo list -m all
go docView documentationgo doc fmt.Println

🎓 Summary

In this chapter, we learned about Go's command-line tools in detail:

  • Basic Commands: version, env, help and other information queries
  • Compilation Commands: build, run, install and other compilation tools
  • Module Management: mod, get and other dependency management
  • Testing Tools: test, vet, fmt and other quality assurance
  • Documentation Tools: doc, generate and other auxiliary tools
  • Practical Workflow: Complete project development workflow

Mastering these tools is a fundamental skill for becoming a Go developer. It is recommended to use these commands frequently in practice, as practice makes perfect.


Next, let's learn about Go Program Structure to understand the basic components and organization of Go programs.

Tips

It is recommended to record commonly used commands and parameters, or create aliases to improve development efficiency:

bash
alias gob='go build'
alias gor='go run'
alias got='go test -v'

Content is for learning and research only.