diff --git a/.specify/memory/constitution.md b/.specify/memory/constitution.md index 8c391d8..01b7581 100644 --- a/.specify/memory/constitution.md +++ b/.specify/memory/constitution.md @@ -1,36 +1,42 @@ # 君鸿卡管系统 Constitution @@ -250,47 +256,6 @@ func (s *Service) GetUserByID(ctx context.Context, id string) (*User, error) { return user, nil } - -// CreateOrder 创建新订单 -func (s *Service) CreateOrder(ctx context.Context, req *CreateOrderRequest) (*Order, error) { - // 开启事务 - tx := s.db.Begin() - defer func() { - if r := recover(); r != nil { - tx.Rollback() - s.logger.Error("创建订单时发生panic", zap.Any("panic", r)) - } - }() - - // 验证库存 - if err := s.validateStock(ctx, req.ProductID, req.Quantity); err != nil { - tx.Rollback() - return nil, fmt.Errorf("库存验证失败: %w", err) - } - - // 创建订单记录 - order := &Order{ - UserID: req.UserID, - ProductID: req.ProductID, - Quantity: req.Quantity, - Status: constants.OrderStatusPending, - } - - if err := tx.Create(order).Error; err != nil { - tx.Rollback() - s.logger.Error("创建订单失败", - zap.String("user_id", req.UserID), - zap.Error(err)) - return nil, err - } - - tx.Commit() - s.logger.Info("订单创建成功", - zap.String("order_id", order.ID), - zap.String("user_id", req.UserID)) - - return order, nil -} ``` **正确的中文日志使用:** @@ -300,10 +265,6 @@ logger.Info("服务启动成功", zap.String("host", cfg.Server.Host), zap.Int("port", cfg.Server.Port)) -logger.Info("配置热重载成功", - zap.String("config_file", "config.yaml"), - zap.Time("reload_time", time.Now())) - // 警告日志 logger.Warn("Redis 连接延迟较高", zap.Duration("latency", latency), @@ -314,95 +275,6 @@ logger.Error("数据库连接失败", zap.String("host", cfg.DB.Host), zap.Int("port", cfg.DB.Port), zap.Error(err)) - -logger.Error("令牌验证失败", - zap.String("token", token[:10]+"..."), - zap.String("client_ip", clientIP), - zap.Error(err)) - -// 调试日志 -logger.Debug("处理用户请求", - zap.String("request_id", requestID), - zap.String("method", c.Method()), - zap.String("path", c.Path()), - zap.String("user_id", userID)) -``` - -**用户可见错误消息(双语支持):** -```go -// pkg/errors/codes.go -var errorMessages = map[int]ErrorMessage{ - CodeSuccess: {"Success", "成功"}, - CodeInternalError: {"Internal server error", "内部服务器错误"}, - CodeMissingToken: {"Missing authentication token", "缺失认证令牌"}, - CodeInvalidToken: {"Invalid or expired token", "令牌无效或已过期"}, - CodeTooManyRequests: {"Too many requests", "请求过于频繁"}, - CodeAuthServiceUnavailable: {"Authentication service unavailable", "认证服务不可用"}, -} - -// 使用时根据语言返回对应消息 -message := errors.GetMessage(code, "zh") // 返回中文消息 -``` - -**错误的英文注释(不推荐):** -```go -// ❌ 全英文注释(可读性较差,不便于中文团队维护) -// GetUserByID retrieves user information by user ID -// Returns NotFoundError if user does not exist -func (s *Service) GetUserByID(ctx context.Context, id string) (*User, error) { - // Validate parameters - if id == "" { - return nil, errors.New(errors.CodeInvalidParam, "用户 ID 不能为空") - } - - // Fetch user from store - user, err := s.store.GetByID(ctx, id) - if err != nil { - s.logger.Error("Failed to get user", // ❌ 英文日志 - zap.String("user_id", id), - zap.Error(err)) - return nil, fmt.Errorf("failed to get user: %w", err) - } - - return user, nil -} -``` - -**例外情况(可使用英文):** -```go -// ✅ 导出的包级别文档注释可使用英文(生态兼容性) -// Package user provides user management functionality. -// It includes user CRUD operations, authentication, and authorization. -package user - -// ✅ 导出的 API 文档注释可使用英文 -// UserService provides user-related business logic operations. -type UserService struct { - store UserStorer - logger *zap.Logger -} - -// ✅ 但内部实现注释应使用中文 -func (s *UserService) Create(ctx context.Context, req *CreateUserRequest) (*User, error) { - // 验证用户输入 - if err := req.Validate(); err != nil { - return nil, err - } - - // 检查用户是否已存在 - existing, _ := s.store.GetByEmail(ctx, req.Email) - if existing != nil { - return nil, errors.New(errors.CodeUserExists, "用户邮箱已存在") - } - - // 创建用户记录 - user := &User{ - Name: req.Name, - Email: req.Email, - } - - return s.store.Create(ctx, user) -} ``` **理由 (RATIONALE):** @@ -417,6 +289,12 @@ func (s *UserService) Create(ctx context.Context, req *CreateUserRequest) (*User 5. **统一业务规则**:确保所有地方使用相同的业务规则值 6. "3 次规则"提供明确的阈值,避免过早优化,同时确保重复值被及时抽取 +使用中文注释和日志的理由: +1. **提高团队效率**:中文开发团队阅读中文注释更快速准确 +2. **降低理解成本**:减少翻译和理解偏差 +3. **改善调试体验**:中文日志更易于排查问题 +4. **保持生态兼容**:导出 API 的文档注释可保留英文 + --- ### III. Testing Standards (测试标准) @@ -950,6 +828,111 @@ Go 语言的设计哲学强调简单性、直接性和实用性。Java 风格的 --- +### VII. Documentation Standards (文档规范) + +**规则 (RULES):** + +- 每个功能完成后 **MUST** 在 `docs/` 目录创建总结文档 +- 总结文档路径 **MUST** 遵循规范:`docs/{feature-id}/` 对应 `specs/{feature-id}/` +- 总结文档文件名 **MUST** 使用中文命名(例如:`功能总结.md`、`使用指南.md`、`架构说明.md`) +- 总结文档内容 **MUST** 使用中文编写 +- 每次添加新功能总结文档时 **MUST** 同步更新 `README.md` +- `README.md` 中的功能描述 **MUST** 简短精炼,让首次接触项目的开发者能快速了解 +- `README.md` 的功能描述 **SHOULD** 控制在 2-3 句话以内 + +**文档结构示例:** + +``` +specs/001-fiber-middleware-integration/ # 功能规划文档(设计阶段) +├── spec.md +├── plan.md +├── tasks.md +└── quickstart.md + +docs/001-fiber-middleware-integration/ # 功能总结文档(完成阶段) +├── 功能总结.md # 功能概述和实现要点 +├── 使用指南.md # 如何使用该功能 +└── 架构说明.md # 架构设计和技术决策(可选) + +README.md # 项目主文档 +## 核心功能 +- **认证中间件**:基于 Redis 的 Token 认证 +- **限流中间件**:基于 IP 的限流,支持可配置的限制和存储后端 +``` + +**正确的文档组织:** + +```markdown + +# 用户管理功能总结 + +## 功能概述 + +实现了完整的用户 CRUD 操作,包括用户创建、查询、更新、删除和列表分页。 + +## 核心实现 + +- Handler: `internal/handler/user.go` +- Service: `internal/service/user.go` +- Store: `internal/store/postgres/user.go` +- Model: `internal/model/user.go` + +## API 端点 + +- `POST /api/v1/users` - 创建用户 +- `GET /api/v1/users/:id` - 获取用户 +- `PUT /api/v1/users/:id` - 更新用户 +- `DELETE /api/v1/users/:id` - 删除用户 +- `GET /api/v1/users` - 用户列表(分页) + +## 技术要点 + +- 使用 GORM 进行数据访问 +- 使用 Validator 进行参数验证 +- 支持事务处理 +- 统一错误处理和响应格式 + +详细使用说明请参阅 [使用指南.md](./使用指南.md) +``` + +```markdown + +## 核心功能 + +- **认证中间件**:基于 Redis 的 Token 认证 +- **限流中间件**:IP 限流,支持 Memory 和 Redis 存储 +- **用户管理**:完整的用户 CRUD 和分页列表功能 +- **日志系统**:Zap 结构化日志,自动轮转和请求追踪 + +详细文档: +- [认证中间件](docs/001-fiber-middleware-integration/功能总结.md) +- [用户管理](docs/002-user-management/功能总结.md) +``` + +**错误的文档组织(禁止):** + +``` +❌ docs/feature-summary.md # 所有功能混在一个文件 +❌ docs/001-summary.md # 英文命名 +❌ docs/001/summary.md # 英文内容 +❌ specs/001.../implementation.md # 总结文档放在 specs/ 下 +❌ README.md 中没有更新新功能 # 遗漏 README 更新 +❌ README.md 功能描述过长(超过 5 句话) # 描述冗长 +``` + +**README.md 更新要求:** + +- **简洁性**:每个功能 2-3 句话描述核心价值 +- **可读性**:使用中文,便于中文开发者快速理解 +- **链接性**:提供到详细文档的链接 +- **分类性**:按功能模块分组(如"核心功能"、"中间件"、"业务模块"等) + +**理由 (RATIONALE):** + +统一的文档结构使新成员快速了解项目功能和架构。中文文档降低中文团队的阅读门槛,提高协作效率。将总结文档与设计文档分离(`docs/` vs `specs/`),清晰区分"计划做什么"和"做了什么"。强制更新 README.md 确保项目主文档始终反映最新功能。简短的 README 描述让首次接触项目的开发者能在 5 分钟内了解项目全貌。 + +--- + ## Development Workflow (开发工作流程) ### 分支管理 @@ -980,6 +963,7 @@ Go 语言的设计哲学强调简单性、直接性和实用性。Java 风格的 - 无安全漏洞(SQL 注入、XSS、命令注入等) - 性能影响可接受 - 代码通过 `gofmt`、`go vet`、`golangci-lint` 检查 + - **文档已按规范更新(docs/ 和 README.md)** --- @@ -1004,6 +988,8 @@ Go 语言的设计哲学强调简单性、直接性和实用性。Java 风格的 - [ ] **无 Java 风格反模式**(无 getter/setter、无不必要接口、无过度抽象) - [ ] **遵循 Go 命名约定**(缩写大小写一致、包名简短、无下划线) - [ ] **使用 Go 惯用并发模式**(goroutines/channels,无线程池类) +- [ ] **功能总结文档已创建**(在 `docs/{feature-id}/` 目录下,中文命名和内容) +- [ ] **README.md 已更新**(添加功能简短描述,2-3 句话) ### 上线前检查 @@ -1038,12 +1024,13 @@ Go 语言的设计哲学强调简单性、直接性和实用性。Java 风格的 - 违反宪章的代码 **MUST** 在合并前修正 - 特别关注 Go 惯用法原则,拒绝 Java 风格的代码 - 特别关注常量使用规范,拒绝不必要的硬编码 +- 特别关注文档规范,确保每个功能都有完整的中文文档 - 任何复杂性增加(新依赖、新架构层)**MUST** 在设计文档中明确说明必要性 ### 运行时开发指导 -开发时参考本宪章确保一致性。如有疑问,优先遵守原则,再讨论例外情况。记住:**写 Go 代码,不是用 Go 语法写 Java**。记住:**定义常量是为了使用,不是为了装饰**。 +开发时参考本宪章确保一致性。如有疑问,优先遵守原则,再讨论例外情况。记住:**写 Go 代码,不是用 Go 语法写 Java**。记住:**定义常量是为了使用,不是为了装饰**。记住:**写文档是为了团队协作,不是为了应付检查**。 --- -**Version**: 2.1.1 | **Ratified**: 2025-11-10 | **Last Amended**: 2025-11-11 +**Version**: 2.2.0 | **Ratified**: 2025-11-10 | **Last Amended**: 2025-11-11 diff --git a/.specify/templates/plan-template.md b/.specify/templates/plan-template.md index db0396f..0b7d137 100644 --- a/.specify/templates/plan-template.md +++ b/.specify/templates/plan-template.md @@ -59,6 +59,13 @@ - [ ] 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 @@ -105,6 +112,7 @@ ### Documentation (this feature) +**设计文档(specs/ 目录)**:开发前的规划和设计 ```text specs/[###-feature]/ ├── plan.md # This file (/speckit.plan command output) @@ -115,6 +123,16 @@ specs/[###-feature]/ └── 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)