Files
photography/backend/docs/CLAUDE.md
xujiang a2f2f66f88
Some checks failed
部署后端服务 / 🧪 测试后端 (push) Failing after 1m37s
部署后端服务 / 🚀 构建并部署 (push) Has been skipped
部署后端服务 / 🔄 回滚部署 (push) Has been skipped
refactor: 重构后端架构,采用 Go 风格四层设计模式
## 主要变更

### 🏗️ 架构重构
- 采用简洁的四层架构:API → Service → Repository → Model
- 遵循 Go 语言最佳实践和命名规范
- 实现依赖注入和接口导向设计
- 统一错误处理和响应格式

### 📁 目录结构优化
- 删除重复模块 (application/, domain/, infrastructure/ 等)
- 规范化命名 (使用 Go 风格的 snake_case)
- 清理无关文件 (package.json, node_modules/ 等)
- 新增规范化的测试目录结构

### 📚 文档系统
- 为每个模块创建详细的 CLAUDE.md 指导文件
- 包含开发规范、最佳实践和使用示例
- 支持模块化开发,缩短上下文长度

### 🔧 开发规范
- 统一接口命名规范 (UserServicer, PhotoRepositoryr)
- 标准化错误处理机制
- 完善的测试策略 (单元测试、集成测试、性能测试)
- 规范化的配置管理

### 🗂️ 新增文件
- cmd/server/ - 服务启动入口和配置
- internal/model/ - 数据模型层 (entity, dto, request)
- pkg/ - 共享工具包 (logger, response, validator)
- tests/ - 完整测试结构
- docs/ - API 文档和架构设计
- .gitignore - Git 忽略文件配置

### 🗑️ 清理内容
- 删除 Node.js 相关文件 (package.json, node_modules/)
- 移除重复的架构目录
- 清理临时文件和构建产物
- 删除重复的文档文件

## 影响
- 提高代码可维护性和可扩展性
- 统一开发规范,提升团队协作效率
- 优化项目结构,符合 Go 语言生态标准
- 完善文档体系,降低上手难度
2025-07-10 11:20:59 +08:00

26 KiB
Raw Blame History

Documentation Module - CLAUDE.md

本文件为 Claude Code 在文档模块中工作时提供指导。

🎯 模块概览

文档模块负责维护项目的技术文档、API 文档和架构设计文档,确保项目的可理解性和可维护性。

主要职责

  • 📚 API 接口文档
  • 🏗️ 架构设计文档
  • 🚀 部署运维文档
  • 📖 开发者指南
  • 📋 变更日志

📁 模块结构

docs/
├── CLAUDE.md                    # 📋 当前文件 - API 文档和接口设计指导
├── api/                         # 📚 API 接口文档
│   ├── openapi.yaml            # OpenAPI 3.0 规范
│   ├── swagger.json            # Swagger JSON 格式
│   ├── postman/                # Postman 集合
│   │   ├── photography.json    # API 测试集合
│   │   └── environment.json    # 环境变量
│   └── examples/               # 请求响应示例
│       ├── user_examples.md    # 用户接口示例
│       ├── photo_examples.md   # 照片接口示例
│       └── auth_examples.md    # 认证接口示例
├── architecture/               # 🏗️ 架构设计文档
│   ├── overview.md             # 系统架构概览
│   ├── database_design.md      # 数据库设计
│   ├── api_design.md          # API 设计原则
│   ├── security.md            # 安全架构
│   └── performance.md         # 性能优化
├── development/                # 👨‍💻 开发文档
│   ├── getting_started.md      # 快速开始
│   ├── coding_standards.md     # 编码规范
│   ├── testing_guide.md        # 测试指南
│   ├── debugging.md           # 调试指南
│   └── contribution.md        # 贡献指南
├── deployment/                 # 🚀 部署文档
│   ├── local_deployment.md     # 本地部署
│   ├── docker_deployment.md    # Docker 部署
│   ├── production_deployment.md # 生产环境部署
│   ├── monitoring.md          # 监控配置
│   └── troubleshooting.md     # 故障排查
├── guides/                     # 📖 使用指南
│   ├── user_management.md      # 用户管理
│   ├── photo_management.md     # 照片管理
│   ├── authentication.md      # 认证授权
│   └── file_upload.md         # 文件上传
├── changelog/                  # 📋 变更日志
│   ├── CHANGELOG.md           # 版本变更记录
│   └── migration_guides/      # 迁移指南
│       ├── v1_to_v2.md        # 版本迁移
│       └── breaking_changes.md # 破坏性变更
└── templates/                  # 📄 文档模板
    ├── api_template.md         # API 文档模板
    ├── guide_template.md       # 指南模板
    └── adr_template.md         # 架构决策记录模板

📚 API 文档

OpenAPI 3.0 规范

# api/openapi.yaml - OpenAPI 3.0 规范
openapi: 3.0.3
info:
  title: Photography Portfolio API
  description: 摄影作品集 REST API
  version: 1.0.0
  contact:
    name: API Support
    email: support@photography.com
  license:
    name: MIT
    url: https://opensource.org/licenses/MIT

servers:
  - url: https://api.photography.com/v1
    description: 生产环境
  - url: https://staging-api.photography.com/v1
    description: 测试环境
  - url: http://localhost:8080/api/v1
    description: 开发环境

paths:
  /users:
    get:
      summary: 获取用户列表
      description: 获取系统中的用户列表,支持分页和过滤
      operationId: listUsers
      tags:
        - Users
      parameters:
        - name: page
          in: query
          description: 页码
          required: false
          schema:
            type: integer
            minimum: 1
            default: 1
        - name: limit
          in: query
          description: 每页数量
          required: false
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 20
        - name: sort
          in: query
          description: 排序字段
          required: false
          schema:
            type: string
            enum: [id, username, email, created_at]
            default: created_at
        - name: order
          in: query
          description: 排序方向
          required: false
          schema:
            type: string
            enum: [asc, desc]
            default: desc
      responses:
        '200':
          description: 成功获取用户列表
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserListResponse'
        '400':
          description: 请求参数错误
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          description: 未授权
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '500':
          description: 服务器内部错误
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
      security:
        - BearerAuth: []
        
    post:
      summary: 创建用户
      description: 创建新用户账户
      operationId: createUser
      tags:
        - Users
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateUserRequest'
      responses:
        '201':
          description: 用户创建成功
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserResponse'
        '400':
          description: 请求参数错误
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ValidationErrorResponse'
        '409':
          description: 用户已存在
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

  /users/{id}:
    get:
      summary: 获取用户详情
      description: 根据用户ID获取用户详细信息
      operationId: getUserById
      tags:
        - Users
      parameters:
        - name: id
          in: path
          description: 用户ID
          required: true
          schema:
            type: integer
            format: int64
      responses:
        '200':
          description: 成功获取用户信息
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserResponse'
        '404':
          description: 用户不存在
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
      security:
        - BearerAuth: []

components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
          format: int64
          description: 用户ID
          example: 1
        username:
          type: string
          description: 用户名
          example: "john_doe"
        email:
          type: string
          format: email
          description: 邮箱地址
          example: "john@example.com"
        first_name:
          type: string
          description: 名字
          example: "John"
        last_name:
          type: string
          description: 姓氏
          example: "Doe"
        avatar:
          type: string
          format: uri
          description: 头像URL
          example: "https://example.com/avatars/john.jpg"
        role:
          type: string
          enum: [admin, editor, user]
          description: 用户角色
          example: "user"
        status:
          type: string
          enum: [active, inactive, banned]
          description: 用户状态
          example: "active"
        created_at:
          type: string
          format: date-time
          description: 创建时间
          example: "2024-01-01T00:00:00Z"
        updated_at:
          type: string
          format: date-time
          description: 更新时间
          example: "2024-01-01T00:00:00Z"
      required:
        - id
        - username
        - email
        - role
        - status
        - created_at
        - updated_at

    CreateUserRequest:
      type: object
      properties:
        username:
          type: string
          minLength: 3
          maxLength: 50
          pattern: '^[a-zA-Z0-9_-]+$'
          description: 用户名
          example: "john_doe"
        email:
          type: string
          format: email
          description: 邮箱地址
          example: "john@example.com"
        password:
          type: string
          minLength: 8
          description: 密码
          example: "SecurePassword123!"
        first_name:
          type: string
          maxLength: 50
          description: 名字
          example: "John"
        last_name:
          type: string
          maxLength: 50
          description: 姓氏
          example: "Doe"
      required:
        - username
        - email
        - password

    UserResponse:
      type: object
      properties:
        success:
          type: boolean
          example: true
        data:
          $ref: '#/components/schemas/User'
        message:
          type: string
          example: "User retrieved successfully"
        timestamp:
          type: integer
          format: int64
          example: 1704067200
        request_id:
          type: string
          example: "req_123456789"

    UserListResponse:
      type: object
      properties:
        success:
          type: boolean
          example: true
        data:
          type: array
          items:
            $ref: '#/components/schemas/User'
        pagination:
          $ref: '#/components/schemas/Pagination'
        message:
          type: string
          example: "Users retrieved successfully"
        timestamp:
          type: integer
          format: int64
          example: 1704067200
        request_id:
          type: string
          example: "req_123456789"

    Pagination:
      type: object
      properties:
        page:
          type: integer
          example: 1
        limit:
          type: integer
          example: 20
        total:
          type: integer
          format: int64
          example: 100
        total_pages:
          type: integer
          example: 5
        has_next:
          type: boolean
          example: true
        has_prev:
          type: boolean
          example: false

    ErrorResponse:
      type: object
      properties:
        success:
          type: boolean
          example: false
        error:
          $ref: '#/components/schemas/Error'
        timestamp:
          type: integer
          format: int64
          example: 1704067200
        request_id:
          type: string
          example: "req_123456789"

    Error:
      type: object
      properties:
        code:
          type: string
          example: "USER_NOT_FOUND"
        message:
          type: string
          example: "User not found"
        details:
          type: string
          example: "User with ID 123 does not exist"

    ValidationErrorResponse:
      type: object
      properties:
        success:
          type: boolean
          example: false
        error:
          type: object
          properties:
            code:
              type: string
              example: "VALIDATION_ERROR"
            message:
              type: string
              example: "Validation failed"
            details:
              type: array
              items:
                $ref: '#/components/schemas/ValidationError'
        timestamp:
          type: integer
          format: int64
          example: 1704067200
        request_id:
          type: string
          example: "req_123456789"

    ValidationError:
      type: object
      properties:
        field:
          type: string
          example: "email"
        value:
          type: string
          example: "invalid-email"
        tag:
          type: string
          example: "email"
        message:
          type: string
          example: "email must be a valid email address"

  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: JWT Bearer token

  parameters:
    PageParam:
      name: page
      in: query
      description: 页码
      required: false
      schema:
        type: integer
        minimum: 1
        default: 1

    LimitParam:
      name: limit
      in: query
      description: 每页数量
      required: false
      schema:
        type: integer
        minimum: 1
        maximum: 100
        default: 20

    SortParam:
      name: sort
      in: query
      description: 排序字段
      required: false
      schema:
        type: string
        default: "created_at"

    OrderParam:
      name: order
      in: query
      description: 排序方向
      required: false
      schema:
        type: string
        enum: [asc, desc]
        default: "desc"

tags:
  - name: Users
    description: 用户管理接口
  - name: Photos
    description: 照片管理接口
  - name: Authentication
    description: 认证授权接口
  - name: Categories
    description: 分类管理接口
  - name: Tags
    description: 标签管理接口

🏗️ 架构设计

系统架构概览

# architecture/overview.md - 系统架构概览

## 整体架构

Photography Portfolio 采用现代化的微服务架构,基于 Go 语言开发,使用 Clean Architecture 设计模式。

### 架构层次

┌─────────────────────────────────────────────────────────────┐ │ Frontend Layer │ │ Next.js + React + TypeScript + Tailwind CSS │ └─────────────────────────────────────────────────────────────┘ │ │ HTTP/HTTPS ▼ ┌─────────────────────────────────────────────────────────────┐ │ API Gateway │ │ Caddy + Load Balancer │ └─────────────────────────────────────────────────────────────┘ │ │ HTTP ▼ ┌─────────────────────────────────────────────────────────────┐ │ Backend Services │ │ │ │ ┌─────────────────┐ ┌─────────────────┐ ┌───────────────┐ │ │ │ User Service │ │ Photo Service │ │ Auth Service │ │ │ │ (Go + Gin) │ │ (Go + Gin) │ │ (Go + Gin) │ │ │ └─────────────────┘ └─────────────────┘ └───────────────┘ │ │ │ └─────────────────────────────────────────────────────────────┘ │ │ SQL/NoSQL ▼ ┌─────────────────────────────────────────────────────────────┐ │ Data Layer │ │ │ │ ┌─────────────────┐ ┌─────────────────┐ ┌───────────────┐ │ │ │ PostgreSQL │ │ Redis │ │ File Storage │ │ │ │ (主数据库) │ │ (缓存) │ │ (S3/Local) │ │ │ └─────────────────┘ └─────────────────┘ └───────────────┘ │ │ │ └─────────────────────────────────────────────────────────────┘


### 核心设计原则

1. **单一职责原则**: 每个服务只负责一个业务领域
2. **依赖倒置原则**: 高层模块不依赖低层模块,都依赖抽象
3. **接口隔离原则**: 使用接口定义契约,便于测试和替换
4. **开闭原则**: 对扩展开放,对修改封闭
5. **最小知识原则**: 模块间耦合度最小化

### 技术栈选择

#### 后端技术栈
- **语言**: Go 1.23+ (性能优异,并发支持)
- **框架**: Gin (轻量级,高性能 HTTP 框架)
- **数据库**: PostgreSQL (关系型数据,事务支持)
- **缓存**: Redis (高性能内存缓存)
- **ORM**: GORM (功能丰富,性能优良)
- **认证**: JWT (无状态,扩展性好)
- **日志**: Uber Zap (结构化,高性能)
- **配置**: Viper (灵活的配置管理)

#### 部署技术栈
- **容器化**: Docker + Docker Compose
- **Web 服务器**: Caddy (自动 HTTPS配置简单)
- **CI/CD**: Gitea Actions (自动化部署)
- **监控**: Prometheus + Grafana (可观测性)

### 数据流向

1. **请求流程**:
   Frontend → API Gateway → Backend Service → Repository → Database

2. **响应流程**:
   Database → Repository → Service → Handler → API Gateway → Frontend

3. **认证流程**:
   Client → Auth Service → JWT Token → Protected Resources

4. **文件上传流程**:
   Client → Upload Handler → Storage Service → File System/S3

数据库设计

# architecture/database_design.md - 数据库设计

## 数据库选择

### PostgreSQL (主数据库)
- **优势**: ACID 事务支持,丰富的数据类型,成熟的生态
- **用途**: 用户数据、照片元数据、分类标签等结构化数据
- **版本**: PostgreSQL 14+

### Redis (缓存数据库)
- **优势**: 高性能内存存储,丰富的数据结构
- **用途**: 会话缓存、频繁查询数据缓存、限流计数器
- **版本**: Redis 6+

## 表结构设计

### 用户表 (users)
```sql
CREATE TABLE users (
    id BIGSERIAL PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    password VARCHAR(255) NOT NULL,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    avatar VARCHAR(255),
    bio TEXT,
    role VARCHAR(20) DEFAULT 'user',
    status VARCHAR(20) DEFAULT 'active',
    last_login_at TIMESTAMP,
    email_verified_at TIMESTAMP,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMP
);

-- 索引
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_username ON users(username);
CREATE INDEX idx_users_status ON users(status);
CREATE INDEX idx_users_created_at ON users(created_at);

照片表 (photos)

CREATE TABLE photos (
    id BIGSERIAL PRIMARY KEY,
    user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    title VARCHAR(255) NOT NULL,
    description TEXT,
    filename VARCHAR(255) NOT NULL,
    file_path VARCHAR(500) NOT NULL,
    file_size BIGINT NOT NULL,
    mime_type VARCHAR(100) NOT NULL,
    width INTEGER DEFAULT 0,
    height INTEGER DEFAULT 0,
    exif_data TEXT,
    taken_at TIMESTAMP,
    location VARCHAR(255),
    camera VARCHAR(100),
    lens VARCHAR(100),
    status VARCHAR(20) DEFAULT 'active',
    view_count INTEGER DEFAULT 0,
    download_count INTEGER DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMP
);

-- 索引
CREATE INDEX idx_photos_user_id ON photos(user_id);
CREATE INDEX idx_photos_status ON photos(status);
CREATE INDEX idx_photos_created_at ON photos(created_at);
CREATE INDEX idx_photos_taken_at ON photos(taken_at);

关系设计

实体关系图

Users ||--o{ Photos : owns
Photos }o--o{ Categories : categorized_by
Photos }o--o{ Tags : tagged_with
Users ||--o{ Albums : creates
Albums }o--o{ Photos : contains

外键约束

  • 所有外键使用 CASCADE 删除策略
  • 确保数据一致性和完整性
  • 使用索引优化查询性能

查询优化

索引策略

  1. 主键索引: 自动创建
  2. 外键索引: 手动创建,优化关联查询
  3. 查询索引: 根据常用查询条件创建
  4. 复合索引: 针对多字段查询优化

查询优化技巧

  1. 避免 N+1 查询: 使用预加载
  2. 分页查询: 使用 LIMIT 和 OFFSET
  3. 条件筛选: 在数据库层面过滤数据
  4. 结果缓存: 缓存频繁查询的结果

## 📖 开发指南

### 快速开始
```markdown
# development/getting_started.md - 快速开始

## 环境要求

### 必需软件
- Go 1.23+
- PostgreSQL 14+
- Redis 6+
- Docker & Docker Compose
- Git

### 推荐工具
- GoLand 或 VS Code
- Postman 或 Insomnia
- DBeaver (数据库管理)
- Redis Desktop Manager

## 本地开发环境设置

### 1. 克隆项目
```bash
git clone <repository-url>
cd photography-backend

2. 安装依赖

go mod download

3. 配置环境

# 复制配置文件
cp configs/config.dev.yaml.example configs/config.dev.yaml

# 修改数据库配置
vim configs/config.dev.yaml

4. 启动服务

# 开发模式 (SQLite)
make dev

# 完整模式 (PostgreSQL + Redis)
make dev-full

# Mock 模式 (无数据库)
make dev-simple

5. 验证安装

# 检查服务状态
curl http://localhost:8080/health

# 预期响应
{
  "status": "healthy",
  "timestamp": "2024-01-01T00:00:00Z",
  "version": "1.0.0"
}

开发流程

1. 功能开发

  1. 创建功能分支: git checkout -b feature/new-feature
  2. 编写代码和测试
  3. 运行测试: make test
  4. 代码检查: make lint
  5. 提交代码: git commit -m "feat: add new feature"

2. 测试验证

# 运行单元测试
make test-unit

# 运行集成测试
make test-integration

# 运行所有测试
make test

# 查看测试覆盖率
make test-coverage

3. 提交代码

# 格式化代码
make fmt

# 代码检查
make lint

# 构建项目
make build

# 提交到远程
git push origin feature/new-feature

## 📋 变更日志

### 版本管理
```markdown
# changelog/CHANGELOG.md - 版本变更记录

# 变更日志

本项目遵循 [语义化版本](https://semver.org/lang/zh-CN/) 规范。

## [未发布]

### 新增
- 新功能开发中...

### 修改
- 改进功能...

### 修复
- 修复问题...

### 删除
- 移除废弃功能...

## [1.2.0] - 2024-01-15

### 新增
- 添加照片批量上传功能
- 支持照片 EXIF 信息提取
- 新增照片搜索 API
- 添加用户头像上传功能
- 支持照片分类管理
- 新增 API 限流中间件

### 修改
- 优化照片列表查询性能
- 改进错误处理机制
- 更新 API 响应格式
- 优化数据库查询索引
- 改进日志记录格式

### 修复
- 修复文件上传大小限制问题
- 解决并发操作的数据竞争问题
- 修复 JWT Token 过期处理
- 解决照片删除时的缓存清理问题
- 修复分页查询的边界条件

### 安全
- 加强文件上传安全验证
- 改进密码强度要求
- 添加请求频率限制
- 优化 SQL 注入防护

## [1.1.0] - 2024-01-01

### 新增
- 用户注册和登录功能
- JWT 认证机制
- 用户权限管理
- 照片上传和管理
- RESTful API 接口
- 数据库迁移系统

### 修改
- 重构代码架构
- 优化性能表现
- 改进错误处理

## [1.0.0] - 2023-12-01

### 新增
- 项目初始版本
- 基础框架搭建
- 核心功能实现

🛠️ 文档维护

文档编写规范

  1. Markdown 格式: 使用标准 Markdown 语法
  2. 结构清晰: 合理使用标题层级
  3. 代码示例: 提供完整可运行的示例
  4. 版本同步: 文档与代码版本保持同步
  5. 定期更新: 定期检查和更新文档内容

文档生成工具

# 生成 API 文档
make docs-api

# 生成 Swagger UI
make docs-swagger

# 生成完整文档站点
make docs-build

# 启动文档服务器
make docs-serve

文档发布流程

  1. 编写文档: 按照模板编写文档
  2. 本地预览: 使用工具预览效果
  3. 代码审查: 提交 PR 进行审查
  4. 自动部署: 合并后自动发布到文档站点

💡 最佳实践

API 文档编写

  1. 完整性: 包含所有接口的详细说明
  2. 示例丰富: 提供请求和响应示例
  3. 错误说明: 详细说明各种错误情况
  4. 版本控制: 明确 API 版本兼容性
  5. 交互式: 支持在线测试功能

架构文档维护

  1. 及时更新: 架构变更后立即更新文档
  2. 图文并茂: 使用图表说明复杂概念
  3. 决策记录: 记录重要的架构决策过程
  4. 影响分析: 说明变更对系统的影响
  5. 迁移指南: 提供版本迁移的详细步骤

开发文档规范

  1. 步骤详细: 提供详细的操作步骤
  2. 环境说明: 明确开发环境要求
  3. 故障排查: 包含常见问题的解决方案
  4. 最佳实践: 分享开发经验和技巧
  5. 持续改进: 根据反馈不断完善文档

本模块确保项目文档的完整性和准确性,为开发者和用户提供清晰的指导。