- 新增统一错误码定义和管理 (pkg/errors/codes.go) - 新增全局错误处理器和中间件 (pkg/errors/handler.go, internal/middleware/error_handler.go) - 新增错误上下文管理 (pkg/errors/context.go) - 增强 Panic 恢复中间件 (internal/middleware/recover.go) - 新增完整的单元测试和集成测试 - 新增功能文档 (docs/003-error-handling/) - 新增功能规范 (specs/003-error-handling/) - 更新 CLAUDE.md 和 README.md
216 lines
9.9 KiB
Markdown
216 lines
9.9 KiB
Markdown
# Implementation Plan: [FEATURE]
|
||
|
||
**Branch**: `[###-feature-name]` | **Date**: [DATE] | **Spec**: [link]
|
||
**Input**: Feature specification from `/specs/[###-feature-name]/spec.md`
|
||
|
||
**Note**: This template is filled in by the `/speckit.plan` command. See `.specify/templates/commands/plan.md` for the execution workflow.
|
||
|
||
## Summary
|
||
|
||
[Extract from feature spec: primary requirement + technical approach from research]
|
||
|
||
## Technical Context
|
||
|
||
<!--
|
||
ACTION REQUIRED: Replace the content in this section with the technical details
|
||
for the project. The structure here is presented in advisory capacity to guide
|
||
the iteration process.
|
||
-->
|
||
|
||
**Language/Version**: [e.g., Python 3.11, Swift 5.9, Rust 1.75 or NEEDS CLARIFICATION]
|
||
**Primary Dependencies**: [e.g., FastAPI, UIKit, LLVM or NEEDS CLARIFICATION]
|
||
**Storage**: [if applicable, e.g., PostgreSQL, CoreData, files or N/A]
|
||
**Testing**: [e.g., pytest, XCTest, cargo test or NEEDS CLARIFICATION]
|
||
**Target Platform**: [e.g., Linux server, iOS 15+, WASM or NEEDS CLARIFICATION]
|
||
**Project Type**: [single/web/mobile - determines source structure]
|
||
**Performance Goals**: [domain-specific, e.g., 1000 req/s, 10k lines/sec, 60 fps or NEEDS CLARIFICATION]
|
||
**Constraints**: [domain-specific, e.g., <200ms p95, <100MB memory, offline-capable or NEEDS CLARIFICATION]
|
||
**Scale/Scope**: [domain-specific, e.g., 10k users, 1M LOC, 50 screens or NEEDS CLARIFICATION]
|
||
|
||
## Constitution Check
|
||
|
||
*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*
|
||
|
||
**Tech Stack Adherence**:
|
||
- [ ] Feature uses Fiber + GORM + Viper + Zap + Lumberjack.v2 + Validator + sonic JSON + Asynq + PostgreSQL
|
||
- [ ] No native calls bypass framework (no `database/sql`, `net/http`, `encoding/json` direct use)
|
||
- [ ] All HTTP operations use Fiber framework
|
||
- [ ] All database operations use GORM
|
||
- [ ] All async tasks use Asynq
|
||
- [ ] Uses Go official toolchain: `go fmt`, `go vet`, `golangci-lint`
|
||
- [ ] Uses Go Modules for dependency management
|
||
|
||
**Code Quality Standards**:
|
||
- [ ] Follows Handler → Service → Store → Model architecture
|
||
- [ ] Handler layer only handles HTTP, no business logic
|
||
- [ ] Service layer contains business logic with cross-module support
|
||
- [ ] Store layer manages all data access with transaction support
|
||
- [ ] Uses dependency injection via struct fields (not constructor patterns)
|
||
- [ ] Unified error codes in `pkg/errors/`
|
||
- [ ] Unified API responses via `pkg/response/`
|
||
- [ ] All constants defined in `pkg/constants/`
|
||
- [ ] All Redis keys managed via key generation functions (no hardcoded strings)
|
||
- [ ] **No hardcoded magic numbers or strings (3+ occurrences must be constants)**
|
||
- [ ] **Defined constants are used instead of hardcoding duplicate values**
|
||
- [ ] **Code comments prefer Chinese for readability (implementation comments in Chinese)**
|
||
- [ ] **Log messages use Chinese (Info/Warn/Error/Debug logs in Chinese)**
|
||
- [ ] **Error messages support Chinese (user-facing errors have Chinese messages)**
|
||
- [ ] All exported functions/types have Go-style doc comments
|
||
- [ ] Code formatted with `gofmt`
|
||
- [ ] Follows Effective Go and Go Code Review Comments
|
||
|
||
**Documentation Standards** (Constitution Principle VII):
|
||
- [ ] Feature summary docs placed in `docs/{feature-id}/` mirroring `specs/{feature-id}/`
|
||
- [ ] Summary doc filenames use Chinese (功能总结.md, 使用指南.md, etc.)
|
||
- [ ] Summary doc content uses Chinese
|
||
- [ ] README.md updated with brief Chinese summary (2-3 sentences)
|
||
- [ ] Documentation is concise for first-time contributors
|
||
|
||
**Go Idiomatic Design**:
|
||
- [ ] Package structure is flat (max 2-3 levels), organized by feature
|
||
- [ ] Interfaces are small (1-3 methods), defined at use site
|
||
- [ ] No Java-style patterns: no I-prefix, no Impl-suffix, no getters/setters
|
||
- [ ] Error handling is explicit (return errors, no panic/recover abuse)
|
||
- [ ] Uses composition over inheritance
|
||
- [ ] Uses goroutines and channels (not thread pools)
|
||
- [ ] Uses `context.Context` for cancellation and timeouts
|
||
- [ ] Naming follows Go conventions: short receivers, consistent abbreviations (URL, ID, HTTP)
|
||
- [ ] No Hungarian notation or type prefixes
|
||
- [ ] Simple constructors (New/NewXxx), no Builder pattern unless necessary
|
||
|
||
**Testing Standards**:
|
||
- [ ] Unit tests for all core business logic (Service layer)
|
||
- [ ] Integration tests for all API endpoints
|
||
- [ ] Tests use Go standard testing framework
|
||
- [ ] Test files named `*_test.go` in same directory
|
||
- [ ] Test functions use `Test` prefix, benchmarks use `Benchmark` prefix
|
||
- [ ] Table-driven tests for multiple test cases
|
||
- [ ] Test helpers marked with `t.Helper()`
|
||
- [ ] Tests are independent (no external service dependencies)
|
||
- [ ] Target coverage: 70%+ overall, 90%+ for core business
|
||
|
||
**User Experience Consistency**:
|
||
- [ ] All APIs use unified JSON response format
|
||
- [ ] Error responses include clear error codes and bilingual messages
|
||
- [ ] RESTful design principles followed
|
||
- [ ] Unified pagination parameters (page, page_size, total)
|
||
- [ ] Time fields use ISO 8601 format (RFC3339)
|
||
- [ ] Currency amounts use integers (cents) to avoid float precision issues
|
||
|
||
**Performance Requirements**:
|
||
- [ ] API response time (P95) < 200ms, (P99) < 500ms
|
||
- [ ] Batch operations use bulk queries/inserts
|
||
- [ ] All database queries have appropriate indexes
|
||
- [ ] List queries implement pagination (default 20, max 100)
|
||
- [ ] Non-realtime operations use async tasks
|
||
- [ ] Database and Redis connection pools properly configured
|
||
- [ ] Uses goroutines/channels for concurrency (not thread pools)
|
||
- [ ] Uses `context.Context` for timeout control
|
||
- [ ] Uses `sync.Pool` for frequently allocated objects
|
||
|
||
**Access Logging Standards** (Constitution Principle VIII):
|
||
- [ ] ALL HTTP requests logged to access.log without exception
|
||
- [ ] Request parameters (query + body) logged (limited to 50KB)
|
||
- [ ] Response parameters (body) logged (limited to 50KB)
|
||
- [ ] Logging happens via centralized Logger middleware (pkg/logger/Middleware())
|
||
- [ ] No middleware bypasses access logging (including auth failures, rate limits)
|
||
- [ ] Body truncation indicates "... (truncated)" when over 50KB limit
|
||
- [ ] Access log includes all required fields: method, path, query, status, duration_ms, request_id, ip, user_agent, user_id, request_body, response_body
|
||
|
||
**Error Handling Standards** (Constitution Principle X):
|
||
- [ ] All API error responses use unified JSON format (via pkg/errors/ global ErrorHandler)
|
||
- [ ] Handler layer errors return error (not manual JSON responses)
|
||
- [ ] Business errors use pkg/errors.New() or pkg/errors.Wrap() with error codes
|
||
- [ ] All error codes defined in pkg/errors/codes.go
|
||
- [ ] All panics caught by Recover middleware and converted to 500 responses
|
||
- [ ] Error logs include complete request context (Request ID, path, method, params)
|
||
- [ ] 5xx server errors auto-sanitized (generic message to client, full error in logs)
|
||
- [ ] 4xx client errors may return specific business messages
|
||
- [ ] No panic in business code (except unrecoverable programming errors)
|
||
- [ ] No manual error response construction in Handler (c.Status().JSON())
|
||
- [ ] Error codes follow classification: 0=success, 1xxx=client (4xx), 2xxx=server (5xx)
|
||
- [ ] Recover middleware registered first in middleware chain
|
||
- [ ] Panic recovery logs complete stack trace
|
||
- [ ] Single request panic does not affect other requests
|
||
|
||
## Project Structure
|
||
|
||
### Documentation (this feature)
|
||
|
||
**设计文档(specs/ 目录)**:开发前的规划和设计
|
||
```text
|
||
specs/[###-feature]/
|
||
├── plan.md # This file (/speckit.plan command output)
|
||
├── research.md # Phase 0 output (/speckit.plan command)
|
||
├── data-model.md # Phase 1 output (/speckit.plan command)
|
||
├── quickstart.md # Phase 1 output (/speckit.plan command)
|
||
├── contracts/ # Phase 1 output (/speckit.plan command)
|
||
└── tasks.md # Phase 2 output (/speckit.tasks command - NOT created by /speckit.plan)
|
||
```
|
||
|
||
**总结文档(docs/ 目录)**:开发完成后的总结和使用指南(遵循 Constitution Principle VII)
|
||
```text
|
||
docs/[###-feature]/
|
||
├── 功能总结.md # 功能概述、核心实现、技术要点(MUST 使用中文命名和内容)
|
||
├── 使用指南.md # 如何使用该功能的详细说明(MUST 使用中文命名和内容)
|
||
└── 架构说明.md # 架构设计和技术决策(可选,MUST 使用中文命名和内容)
|
||
```
|
||
|
||
**README.md 更新**:每次完成功能后 MUST 在 README.md 添加简短描述(2-3 句话,中文)
|
||
|
||
### Source Code (repository root)
|
||
<!--
|
||
ACTION REQUIRED: Replace the placeholder tree below with the concrete layout
|
||
for this feature. Delete unused options and expand the chosen structure with
|
||
real paths (e.g., apps/admin, packages/something). The delivered plan must
|
||
not include Option labels.
|
||
-->
|
||
|
||
```text
|
||
# [REMOVE IF UNUSED] Option 1: Single project (DEFAULT)
|
||
src/
|
||
├── models/
|
||
├── services/
|
||
├── cli/
|
||
└── lib/
|
||
|
||
tests/
|
||
├── contract/
|
||
├── integration/
|
||
└── unit/
|
||
|
||
# [REMOVE IF UNUSED] Option 2: Web application (when "frontend" + "backend" detected)
|
||
backend/
|
||
├── src/
|
||
│ ├── models/
|
||
│ ├── services/
|
||
│ └── api/
|
||
└── tests/
|
||
|
||
frontend/
|
||
├── src/
|
||
│ ├── components/
|
||
│ ├── pages/
|
||
│ └── services/
|
||
└── tests/
|
||
|
||
# [REMOVE IF UNUSED] Option 3: Mobile + API (when "iOS/Android" detected)
|
||
api/
|
||
└── [same as backend above]
|
||
|
||
ios/ or android/
|
||
└── [platform-specific structure: feature modules, UI flows, platform tests]
|
||
```
|
||
|
||
**Structure Decision**: [Document the selected structure and reference the real
|
||
directories captured above]
|
||
|
||
## Complexity Tracking
|
||
|
||
> **Fill ONLY if Constitution Check has violations that must be justified**
|
||
|
||
| Violation | Why Needed | Simpler Alternative Rejected Because |
|
||
|-----------|------------|-------------------------------------|
|
||
| [e.g., 4th project] | [current need] | [why 3 projects insufficient] |
|
||
| [e.g., Repository pattern] | [specific problem] | [why direct DB access insufficient] |
|