go

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Go Development Skill

Go 开发技能指南

You are a Go development specialist. This skill provides comprehensive guidance for Go development workflows, testing, and tooling.
你是一名Go开发专家。本技能为Go开发工作流、测试及工具使用提供全面指导。

Testing Workflow

测试工作流

STRONGLY PREFERRED: Use
gotestsum
for all test execution.
强烈推荐:所有测试执行均使用
gotestsum

Running Tests with gotestsum

使用gotestsum运行测试

bash
undefined
bash
undefined

Basic test run (PREFERRED)

基础测试运行(推荐)

gotestsum ./...
gotestsum ./...

Short alias (if configured)

简短别名(若已配置)

gt ./...
gt ./...

Verbose output

详细输出

gotestsum -v ./...
gotestsum -v ./...

Run specific test

运行指定测试

gotestsum -run TestFunctionName ./...
gotestsum -run TestFunctionName ./...

Run tests in a specific package

运行指定包内的测试

gotestsum ./pkg/mypackage/...
gotestsum ./pkg/mypackage/...

Watch mode (rerun on file changes)

监听模式(文件变更时重新运行)

gotestsum --watch ./...
undefined
gotestsum --watch ./...
undefined

Test Output Formats

测试输出格式

bash
undefined
bash
undefined

Default format (clean, colorized)

默认格式(简洁、带颜色)

gotestsum ./...
gotestsum ./...

Show only test names

仅显示测试名称

gotestsum --format testname ./...
gotestsum --format testname ./...

Dots format (. for pass, F for fail)

点格式(.表示通过,F表示失败)

gotestsum --format dots ./...
gotestsum --format dots ./...

Group by package

按包分组

gotestsum --format pkgname ./...
gotestsum --format pkgname ./...

Standard go test format (with colors)

标准go test格式(带颜色)

gotestsum --format standard ./...
gotestsum --format standard ./...

TestDox format (BDD-style output)

TestDox格式(BDD风格输出)

gotestsum --format testdox ./...
undefined
gotestsum --format testdox ./...
undefined

Common Test Options

常用测试选项

bash
undefined
bash
undefined

Run with race detection

启用竞争检测

gotestsum -race ./...
gotestsum -race ./...

Generate coverage

生成覆盖率报告

gotestsum -cover ./... gotestsum -coverprofile=coverage.out ./...
gotestsum -cover ./... gotestsum -coverprofile=coverage.out ./...

Verbose output

详细输出

gotestsum -v ./...
gotestsum -v ./...

Short mode (skip long-running tests)

短模式(跳过耗时较长的测试)

gotestsum -short ./...
gotestsum -short ./...

Fail fast (stop on first failure)

快速失败(首次失败即停止)

gotestsum --fail-fast ./...
gotestsum --fail-fast ./...

Run tests multiple times

多次运行测试

gotestsum --count=10 ./...
gotestsum --count=10 ./...

Parallel execution

并行执行

gotestsum -p 4 ./...
gotestsum -p 4 ./...

Timeout

超时设置

gotestsum -timeout 30s ./...
undefined
gotestsum -timeout 30s ./...
undefined

Watch Mode for TDD

TDD监听模式

bash
undefined
bash
undefined

Watch and rerun tests on file changes

监听文件变更并重新运行测试

gotestsum --watch ./...
gotestsum --watch ./...

Watch specific package

监听指定包

gotestsum --watch ./pkg/mypackage/...
gotestsum --watch ./pkg/mypackage/...

Watch with specific format

使用指定格式监听

gotestsum --watch --format testdox ./...
undefined
gotestsum --watch --format testdox ./...
undefined

Fallback to go test

回退到go test

If
gotestsum
is not available, use
go test
:
bash
undefined
如果
gotestsum
不可用,可使用
go test
bash
undefined

Basic test run

基础测试运行

go test ./...
go test ./...

Verbose

详细输出

go test -v ./...
go test -v ./...

With coverage

生成覆盖率

go test -cover ./...

**Note:** Always prefer `gotestsum` when available for better output formatting and colors.
go test -cover ./...

**注意:** 只要`gotestsum`可用,优先使用它,因为它的输出格式更友好且带颜色。

Development Workflow

开发工作流

Standard Go Commands

标准Go命令

bash
undefined
bash
undefined

Build the project

构建项目

go build ./...
go build ./...

Check compilation without building

检查编译(不实际构建)

go check ./...
go check ./...

Run the application

运行应用

go run ./cmd/myapp
go run ./cmd/myapp

Install binary

安装二进制文件

go install ./cmd/myapp
go install ./cmd/myapp

Format code

格式化代码

go fmt ./... gofmt -w .
go fmt ./... gofmt -w .

Vet code for issues

检查代码问题

go vet ./...
undefined
go vet ./...
undefined

Module Management

模块管理

bash
undefined
bash
undefined

Initialize module

初始化模块

go mod init github.com/user/project
go mod init github.com/user/project

Add dependencies

添加依赖

go get github.com/some/package@v1.2.3
go get github.com/some/package@v1.2.3

Update dependencies

更新依赖

go get -u ./...
go get -u ./...

Tidy dependencies (remove unused)

整理依赖(移除未使用的依赖)

go mod tidy
go mod tidy

Vendor dependencies

托管依赖

go mod vendor
go mod vendor

Verify dependencies

验证依赖

go mod verify
go mod verify

Download dependencies

下载依赖

go mod download
undefined
go mod download
undefined

Building

构建操作

bash
undefined
bash
undefined

Build current package

构建当前包

go build
go build

Build with output path

指定输出路径构建

go build -o bin/myapp ./cmd/myapp
go build -o bin/myapp ./cmd/myapp

Build all packages

构建所有包

go build ./...
go build ./...

Cross-compile

交叉编译

GOOS=linux GOARCH=amd64 go build -o bin/myapp-linux ./cmd/myapp
GOOS=linux GOARCH=amd64 go build -o bin/myapp-linux ./cmd/myapp

Build with version info

携带版本信息构建

go build -ldflags "-X main.version=1.2.3" ./cmd/myapp
go build -ldflags "-X main.version=1.2.3" ./cmd/myapp

Static binary (no CGO)

静态二进制文件(禁用CGO)

CGO_ENABLED=0 go build -o bin/myapp ./cmd/myapp
undefined
CGO_ENABLED=0 go build -o bin/myapp ./cmd/myapp
undefined

Code Quality

代码质量

bash
undefined
bash
undefined

Format code

格式化代码

go fmt ./...
go fmt ./...

Vet for issues

检查代码问题

go vet ./...
go vet ./...

Run staticcheck (if installed)

运行staticcheck(若已安装)

staticcheck ./...
staticcheck ./...

Run golangci-lint (if installed)

运行golangci-lint(若已安装)

golangci-lint run
golangci-lint run

Check imports

检查导入

goimports -w .
undefined
goimports -w .
undefined

Testing Best Practices

测试最佳实践

Test File Organization

测试文件组织

go
// mypackage_test.go
package mypackage_test  // External tests (test public API)

// Or
package mypackage       // Internal tests (test private functions)
go
// mypackage_test.go
package mypackage_test  // 外部测试(测试公开API)

// 或者
package mypackage       // 内部测试(测试私有函数)

Writing Tests

编写测试

go
// Table-driven tests (PREFERRED)
func TestMyFunction(t *testing.T) {
    tests := []struct {
        name    string
        input   string
        want    string
        wantErr bool
    }{
        {
            name:  "valid input",
            input: "hello",
            want:  "HELLO",
        },
        {
            name:    "empty input",
            input:   "",
            wantErr: true,
        },
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := MyFunction(tt.input)
            if (err != nil) != tt.wantErr {
                t.Errorf("MyFunction() error = %v, wantErr %v", err, tt.wantErr)
                return
            }
            if got != tt.want {
                t.Errorf("MyFunction() = %v, want %v", got, tt.want)
            }
        })
    }
}
go
// 表驱动测试(推荐)
func TestMyFunction(t *testing.T) {
    tests := []struct {
        name    string
        input   string
        want    string
        wantErr bool
    }{
        {
            name:  "valid input",
            input: "hello",
            want:  "HELLO",
        },
        {
            name:    "empty input",
            input:   "",
            wantErr: true,
        },
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := MyFunction(tt.input)
            if (err != nil) != tt.wantErr {
                t.Errorf("MyFunction() error = %v, wantErr %v", err, tt.wantErr)
                return
            }
            if got != tt.want {
                t.Errorf("MyFunction() = %v, want %v", got, tt.want)
            }
        })
    }
}

Test Helpers

测试辅助工具

go
// Use t.Helper() to mark test helpers
func assertNoError(t *testing.T, err error) {
    t.Helper()
    if err != nil {
        t.Fatalf("unexpected error: %v", err)
    }
}

// Use t.Cleanup() for teardown
func TestWithCleanup(t *testing.T) {
    tmpDir := setupTempDir(t)
    t.Cleanup(func() {
        os.RemoveAll(tmpDir)
    })
    // test code
}
go
// 使用t.Helper()标记测试辅助函数
func assertNoError(t *testing.T, err error) {
    t.Helper()
    if err != nil {
        t.Fatalf("unexpected error: %v", err)
    }
}

// 使用t.Cleanup()进行清理操作
func TestWithCleanup(t *testing.T) {
    tmpDir := setupTempDir(t)
    t.Cleanup(func() {
        os.RemoveAll(tmpDir)
    })
    // 测试代码
}

Benchmarks

基准测试

bash
undefined
bash
undefined

Run benchmarks

运行基准测试

gotestsum -bench=. ./...
gotestsum -bench=. ./...

Or with go test

或者使用go test

go test -bench=. ./...
go test -bench=. ./...

Benchmark with memory allocation stats

带内存分配统计的基准测试

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

Run specific benchmark

运行指定基准测试

go test -bench=BenchmarkMyFunction ./...
undefined
go test -bench=BenchmarkMyFunction ./...
undefined

Common Workflows

常用工作流

TDD Workflow

TDD工作流

bash
undefined
bash
undefined

1. Start watch mode

1. 启动监听模式

gotestsum --watch --format testdox ./...
gotestsum --watch --format testdox ./...

2. Write failing test

2. 编写失败的测试

3. Write code to make test pass

3. 编写代码使测试通过

4. Refactor

4. 重构代码

5. Repeat

5. 重复上述步骤

undefined
undefined

Pre-commit Checks

提交前检查

bash
undefined
bash
undefined

Format, vet, and test

格式化、检查并测试

go fmt ./... && go vet ./... && gotestsum ./...
go fmt ./... && go vet ./... && gotestsum ./...

With race detection and coverage

带竞争检测和覆盖率检查

go fmt ./... && go vet ./... && gotestsum -race -cover ./...
undefined
go fmt ./... && go vet ./... && gotestsum -race -cover ./...
undefined

Coverage Analysis

覆盖率分析

bash
undefined
bash
undefined

Generate coverage report

生成覆盖率报告

gotestsum -coverprofile=coverage.out ./...
gotestsum -coverprofile=coverage.out ./...

View coverage in browser

在浏览器中查看覆盖率

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

Show coverage per function

查看每个函数的覆盖率

go tool cover -func=coverage.out
go tool cover -func=coverage.out

Check coverage percentage

检查覆盖率百分比

go tool cover -func=coverage.out | grep total
undefined
go tool cover -func=coverage.out | grep total
undefined

Debugging Tests

调试测试

bash
undefined
bash
undefined

Run specific test with verbose output

运行指定测试并显示详细输出

gotestsum -v -run TestSpecificFunction ./...
gotestsum -v -run TestSpecificFunction ./...

Run tests with print debugging

运行测试并打印调试信息

gotestsum -v ./... 2>&1 | grep "DEBUG"
gotestsum -v ./... 2>&1 | grep "DEBUG"

Use delve for debugging

使用delve进行调试

dlv test ./pkg/mypackage -- -test.run TestSpecificFunction
undefined
dlv test ./pkg/mypackage -- -test.run TestSpecificFunction
undefined

Environment Variables

环境变量

bash
undefined
bash
undefined

Disable CGO

禁用CGO

export CGO_ENABLED=0
export CGO_ENABLED=0

Set GOOS/GOARCH for cross-compilation

设置GOOS/GOARCH用于交叉编译

export GOOS=linux export GOARCH=amd64
export GOOS=linux export GOARCH=amd64

Set Go module proxy

设置Go模块代理

Private modules

私有模块

export GOPRIVATE=github.com/myorg/*
export GOPRIVATE=github.com/myorg/*

Module download mode

模块下载缓存路径

export GOMODCACHE=$HOME/go/pkg/mod
undefined
export GOMODCACHE=$HOME/go/pkg/mod
undefined

gotestsum Advanced Features

gotestsum高级功能

Custom Test Commands

自定义测试命令

bash
undefined
bash
undefined

Run tests with custom go test flags

使用自定义go test标志运行测试

gotestsum -- -tags integration ./...
gotestsum -- -tags integration ./...

Run with build constraints

使用构建约束运行

gotestsum -- -tags "integration e2e" ./...
gotestsum -- -tags "integration e2e" ./...

JSON output for parsing

输出JSON格式结果(用于解析)

gotestsum --jsonfile=test-results.json ./...
gotestsum --jsonfile=test-results.json ./...

JUnit XML output (for CI)

输出JUnit XML格式结果(用于CI)

gotestsum --junitfile=junit.xml ./...
undefined
gotestsum --junitfile=junit.xml ./...
undefined

Rerun Failed Tests

重新运行失败的测试

bash
undefined
bash
undefined

Run tests and save failures

运行测试并保存失败记录

gotestsum --rerun-fails ./...
gotestsum --rerun-fails ./...

Rerun only failed tests from previous run

仅重新运行上一次失败的测试

gotestsum --rerun-fails=2 ./...
undefined
gotestsum --rerun-fails=2 ./...
undefined

Post-run Commands

测试后命令

bash
undefined
bash
undefined

Run command after tests

测试完成后运行命令

gotestsum --post-run-command='notify-send "Tests done"' ./...
gotestsum --post-run-command='notify-send "Tests done"' ./...

Multiple commands

运行多个命令

gotestsum --post-run-command='echo "Tests complete" && ./deploy.sh' ./...
undefined
gotestsum --post-run-command='echo "Tests complete" && ./deploy.sh' ./...
undefined

Quick Reference

快速参考

bash
undefined
bash
undefined

Test with gotestsum (PREFERRED)

使用gotestsum测试(推荐)

gotestsum ./... gt ./... # If alias configured
gotestsum ./... gt ./... # 若已配置别名

Watch mode for TDD

TDD监听模式

gotestsum --watch ./...
gotestsum --watch ./...

Race detection

竞争检测

gotestsum -race ./...
gotestsum -race ./...

Coverage

覆盖率检查

gotestsum -cover ./...
gotestsum -cover ./...

Verbose output

详细输出

gotestsum -v ./...
gotestsum -v ./...

Specific test

指定测试

gotestsum -run TestName ./...
gotestsum -run TestName ./...

Fail fast

快速失败

gotestsum --fail-fast ./...
gotestsum --fail-fast ./...

Format code

格式化代码

go fmt ./...
go fmt ./...

Vet code

检查代码

go vet ./...
go vet ./...

Build

构建项目

go build ./...
go build ./...

Run

运行应用

go run ./cmd/myapp
go run ./cmd/myapp

Module tidy

整理依赖

go mod tidy
undefined
go mod tidy
undefined

Best Practices

最佳实践

  1. Use gotestsum for all testing - Better output, colors, and features
  2. Write table-driven tests - More maintainable and comprehensive
  3. Use t.Helper() for test utilities - Clearer test failure locations
  4. Run tests with -race - Catch race conditions early
  5. Check coverage - Aim for high test coverage
  6. Use go fmt - Consistent code formatting
  7. Run go vet - Catch common mistakes
  8. Keep tests fast - Use -short flag for quick feedback loops
  9. Use subtests with t.Run() - Better organization and parallel execution
  10. Clean up with t.Cleanup() - Proper resource management
  1. 所有测试均使用gotestsum - 输出更友好、带颜色且功能更丰富
  2. 编写表驱动测试 - 更易于维护且覆盖全面
  3. 为测试工具函数使用t.Helper() - 使测试失败位置更清晰
  4. 使用-race标志运行测试 - 尽早发现竞态条件
  5. 检查覆盖率 - 追求高测试覆盖率
  6. 使用go fmt - 保持代码格式一致
  7. 运行go vet - 发现常见代码错误
  8. 保持测试快速 - 使用-short标志获取快速反馈
  9. 使用t.Run()编写子测试 - 组织更清晰且支持并行执行
  10. 使用t.Cleanup()进行清理 - 正确管理资源

CI/CD Integration

CI/CD集成

bash
undefined
bash
undefined

Typical CI test command

典型CI测试命令

gotestsum --format pkgname --junitfile junit.xml -- -race -cover -coverprofile=coverage.out ./...
gotestsum --format pkgname --junitfile junit.xml -- -race -cover -coverprofile=coverage.out ./...

Generate coverage report

生成覆盖率报告

go tool cover -html=coverage.out -o coverage.html
go tool cover -html=coverage.out -o coverage.html

Check coverage threshold

检查覆盖率阈值

go tool cover -func=coverage.out | awk '/total:/ {if ($3+0 < 80.0) exit 1}'
undefined
go tool cover -func=coverage.out | awk '/total:/ {if ($3+0 < 80.0) exit 1}'
undefined