Go 语言以简洁和高性能著称,Claude Code 对 Go 的惯用法(idiomatic Go)理解深入, 能生成符合 Go 社区规范的代码。本文覆盖完整的 Go 开发工作流。
CLAUDE.md 配置(Go 项目)
markdown
## Go 技术规范
- Go 版本:1.22+
- 模块名:github.com/yourorg/yourrepo
- 框架:Gin(Web API)/ Cobra(CLI)
- 数据库:GORM + PostgreSQL
- 测试:标准库 testing + testify
## Go 代码规范
- 遵循 Effective Go 和 Go Code Review Comments
- 错误必须处理,不用 _ 忽略(除非有明确注释说明理由)
- 接口定义在使用方,不在实现方
- goroutine 必须有退出机制(context 取消或 channel close)
- 所有公共函数/类型必须有 godoc 注释
## 命令
- 运行:go run ./cmd/server
- 测试:go test ./... -v -race
- 构建:go build -o bin/server ./cmd/server
- Lint:golangci-lint run工作流 1:生成 REST API(Gin 框架)
Create a REST API with Gin for a blog platform:
Entities: Post (id, title, content, authorId, createdAt, tags[])
User (id, name, email, passwordHash)
Endpoints:
POST /api/auth/register
POST /api/auth/login -> returns JWT
GET /api/posts -> list with pagination (page, limit, tag filter)
POST /api/posts -> create (auth required)
GET /api/posts/:id
PUT /api/posts/:id -> update (owner only)
DELETE /api/posts/:id -> delete (owner only)
Requirements:
- JWT middleware for protected routes
- Request validation with binding tags
- GORM + PostgreSQL
- Structured error responses: {error: string, code: string}
- Graceful shutdown (handle SIGTERM)
Project structure:
cmd/server/main.go
internal/handler/, internal/service/, internal/repository/, internal/model/
工作流 2:并发模式
Implement a worker pool for processing jobs concurrently in Go:
Requirements:
- Fixed number of workers (configurable)
- Job queue with buffered channel
- Context cancellation support (graceful shutdown)
- Error collection from workers
- Progress tracking (processed/total/errors)
- Timeout per job
Use case: process 10,000 image files concurrently with 20 workers.
Show the implementation and usage example.
生成示例:
go
type WorkerPool struct {
workers int
jobs chan Job
results chan Result
wg sync.WaitGroup
}
func (p *WorkerPool) Run(ctx context.Context) {
for i := 0; i < p.workers; i++ {
p.wg.Add(1)
go p.worker(ctx)
}
}
func (p *WorkerPool) worker(ctx context.Context) {
defer p.wg.Done()
for {
select {
case job, ok := <-p.jobs:
if !ok {
return
}
result := job.Process()
p.results <- result
case <-ctx.Done():
return
}
}
}工作流 3:CLI 工具(Cobra)
Create a CLI tool with Cobra for database migration management:
Commands:
migrate up # Run all pending migrations
migrate down [steps] # Rollback N steps (default 1)
migrate status # Show applied/pending migrations
migrate create <name> # Create new migration file
migrate reset # Rollback all + re-apply
Flags:
--config / -c Path to config file (default: ./config.yaml)
--db Database URL override
--dry-run Show what would happen without executing
--verbose / -v Show SQL statements
Config file: YAML with database connection info
Migration files: SQL files in migrations/ directory (001_create_users.up.sql etc.)
Use cobra + viper for config, standard database/sql for migrations.
工作流 4:接口设计(Go 惯用法)
Design a storage interface for a caching layer:
The storage layer should support multiple backends:
1. In-memory (for testing)
2. Redis (for production)
3. File-based (for CLI tools)
Follow Go interface best practices:
- Define interface at the usage site (not in the implementation package)
- Keep interfaces small (interface segregation)
- Return errors, not panics
- Use context for cancellation
Generate:
1. Interface definition
2. In-memory implementation with TTL support
3. Redis implementation using go-redis
4. Mock for testing (manually written, no mockgen)
5. Example usage with dependency injection
工作流 5:错误处理
Review this Go code for error handling issues:
[粘贴代码]
Check for:
1. Ignored errors (assignments to _)
2. Errors wrapped without context (use fmt.Errorf("doing X: %w", err))
3. Panic instead of error return
4. Missing error type assertions where behavior depends on error type
5. Sentinel errors that should be wrapped types instead
Fix all issues following the Go 1.13+ errors package conventions.
Add custom error types where appropriate.
工作流 6:性能测试
Write benchmarks for the critical path in this service:
[粘贴核心函数]
Create _test.go file with:
1. BenchmarkXxx functions for each critical operation
2. Table-driven benchmarks for different input sizes (10, 100, 1000, 10000)
3. Memory allocation tracking (b.ReportAllocs())
4. Parallel benchmark variant (b.RunParallel)
Also add pprof endpoint to the HTTP server for production profiling:
- /debug/pprof/
- /debug/pprof/profile (CPU)
- /debug/pprof/heap
Run: go test -bench=. -benchmem -cpuprofile=cpu.out
go tool pprof cpu.out
工作流 7:静态编译 + Docker 最小镜像
Create a production Dockerfile for this Go service.
Requirements:
- Multi-stage build
- Stage 1: Build with Go 1.22 (static binary, no CGO)
- Stage 2: Scratch or distroless base (final image < 20MB)
- Non-root user
- Copy only the binary + required files (config, migrations)
- Build args for version injection
Also generate a Makefile with targets:
make build # local binary
make docker # build docker image
make test # run tests with race detector
make lint # golangci-lint
make release # tag + push
来源:Anthropic 官方文档 + Go 官方文档