Go 微服务 — 项目 CLAUDE.md¶
使用 PostgreSQL、gRPC、Docker 的 Go 微服务真实世界示例。 请将其复制到项目根目录,并根据服务进行自定义。
项目概览¶
技术栈: Go 1.22+, PostgreSQL, gRPC + REST (grpc-gateway), Docker, sqlc(类型安全 SQL), Wire(依赖注入)
架构: 具有领域、仓储、服务、处理器层的整洁架构。以 gRPC 作为主要传输方式,并为外部客户端提供 REST 网关。
重要规则¶
Go 规范¶
- 遵循 Effective Go 和 Go Code Review Comments 指南
- 错误包装使用
errors.New/fmt.Errorf中的%w— 禁止对错误进行字符串匹配 - 不使用
init()函数 — 在main()或构造函数中显式初始化 - 不使用全局可变状态 — 通过构造函数传递依赖
- 将 context 作为第一个参数,并在所有层中传播
数据库¶
- 所有查询以纯 SQL 形式写在
queries/中 — sqlc 生成类型安全的 Go 代码 migrations/中的迁移使用 golang-migrate — 不要直接修改数据库- 对于多步操作,使用
pgx.Tx进行事务 - 所有查询使用参数化占位符(
$1,$2) — 禁止字符串格式化
错误处理¶
- 不要 panic,返回错误 — panic 仅用于真正不可恢复的情况
- 连同上下文一起包装错误:
fmt.Errorf("creating user: %w", err) - 在
domain/errors.go中定义业务逻辑用的哨兵错误 - 在处理器层将领域错误映射为 gRPC 状态码
// ドメインレイヤー — センチネルエラー
var (
ErrUserNotFound = errors.New("user not found")
ErrEmailTaken = errors.New("email already registered")
)
// ハンドラーレイヤー — gRPCステータスにマップ
func toGRPCError(err error) error {
switch {
case errors.Is(err, domain.ErrUserNotFound):
return status.Error(codes.NotFound, err.Error())
case errors.Is(err, domain.ErrEmailTaken):
return status.Error(codes.AlreadyExists, err.Error())
default:
return status.Error(codes.Internal, "internal error")
}
}
代码风格¶
- 不要在代码或注释中使用表情符号
- 导出的类型和函数需要文档注释
- 函数保持在 50 行以内 — 提取辅助函数
- 对所有具有多种情况的逻辑使用表驱动测试
- 信号通道优先使用
struct{}而不是bool
文件结构¶
cmd/
server/
main.go # エントリーポイント、Wire注入、グレースフルシャットダウン
internal/
domain/ # ビジネス型とインターフェース
user.go # ユーザーエンティティとリポジトリインターフェース
errors.go # センチネルエラー
service/ # ビジネスロジック
user_service.go
user_service_test.go
repository/ # データアクセス(sqlc生成 + カスタム)
postgres/
user_repo.go
user_repo_test.go # testcontainersを使用した統合テスト
handler/ # gRPC + RESTハンドラー
grpc/
user_handler.go
rest/
user_handler.go
config/ # 設定の読み込み
config.go
proto/ # Protobuf定義
user/v1/
user.proto
queries/ # sqlc用SQLクエリ
user.sql
migrations/ # データベースマイグレーション
001_create_users.up.sql
001_create_users.down.sql
主要模式¶
仓储接口¶
type UserRepository interface {
Create(ctx context.Context, user *User) error
FindByID(ctx context.Context, id uuid.UUID) (*User, error)
FindByEmail(ctx context.Context, email string) (*User, error)
Update(ctx context.Context, user *User) error
Delete(ctx context.Context, id uuid.UUID) error
}
带依赖注入的服务¶
type UserService struct {
repo domain.UserRepository
hasher PasswordHasher
logger *slog.Logger
}
func NewUserService(repo domain.UserRepository, hasher PasswordHasher, logger *slog.Logger) *UserService {
return &UserService{repo: repo, hasher: hasher, logger: logger}
}
func (s *UserService) Create(ctx context.Context, req CreateUserRequest) (*domain.User, error) {
existing, err := s.repo.FindByEmail(ctx, req.Email)
if err != nil && !errors.Is(err, domain.ErrUserNotFound) {
return nil, fmt.Errorf("checking email: %w", err)
}
if existing != nil {
return nil, domain.ErrEmailTaken
}
hashed, err := s.hasher.Hash(req.Password)
if err != nil {
return nil, fmt.Errorf("hashing password: %w", err)
}
user := &domain.User{
ID: uuid.New(),
Name: req.Name,
Email: req.Email,
Password: hashed,
}
if err := s.repo.Create(ctx, user); err != nil {
return nil, fmt.Errorf("creating user: %w", err)
}
return user, nil
}
表驱动测试¶
func TestUserService_Create(t *testing.T) {
tests := []struct {
name string
req CreateUserRequest
setup func(*MockUserRepo)
wantErr error
}{
{
name: "valid user",
req: CreateUserRequest{Name: "Alice", Email: "alice@example.com", Password: "secure123"},
setup: func(m *MockUserRepo) {
m.On("FindByEmail", mock.Anything, "alice@example.com").Return(nil, domain.ErrUserNotFound)
m.On("Create", mock.Anything, mock.Anything).Return(nil)
},
wantErr: nil,
},
{
name: "duplicate email",
req: CreateUserRequest{Name: "Alice", Email: "taken@example.com", Password: "secure123"},
setup: func(m *MockUserRepo) {
m.On("FindByEmail", mock.Anything, "taken@example.com").Return(&domain.User{}, nil)
},
wantErr: domain.ErrEmailTaken,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
repo := new(MockUserRepo)
tt.setup(repo)
svc := NewUserService(repo, &bcryptHasher{}, slog.Default())
_, err := svc.Create(context.Background(), tt.req)
if tt.wantErr != nil {
assert.ErrorIs(t, err, tt.wantErr)
} else {
assert.NoError(t, err)
}
})
}
}
环境变量¶
# データベース
DATABASE_URL=postgres://user:pass@localhost:5432/myservice?sslmode=disable
# gRPC
GRPC_PORT=50051
REST_PORT=8080
# 認証
JWT_SECRET= # 本番環境ではvaultから読み込む
TOKEN_EXPIRY=24h
# オブザーバビリティ
LOG_LEVEL=info # debug, info, warn, error
OTEL_ENDPOINT= # OpenTelemetryコレクター
测试策略¶
测试命令¶
# ユニットテスト(高速、外部依存なし)
go test ./internal/... -short -count=1
# 統合テスト(testcontainers用にDockerが必要)
go test ./internal/repository/... -count=1 -timeout 120s
# カバレッジ付きすべてのテスト
go test ./... -coverprofile=coverage.out -count=1
go tool cover -func=coverage.out # サマリー
go tool cover -html=coverage.out # ブラウザ
# レースディテクター
go test ./... -race -count=1
ECC 工作流¶
# 計画
/plan "Add rate limiting to user endpoints"
# 開発
/go-test # Go固有パターンでのTDD
# レビュー
/go-review # Goのイディオム、エラーハンドリング、並行処理
/security-scan # シークレットと脆弱性
# マージ前
go vet ./...
staticcheck ./...
Git 工作流¶
feat:新功能、fix:修复缺陷、refactor:代码重构- 从
main切出功能分支,需要 PR - CI:
go vet、staticcheck、go test -race、golangci-lint - 部署:在 CI 中构建 Docker 镜像并部署到 Kubernetes
本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 ev/ECC