topfans/backend/swagger/README.md
2026-04-07 22:29:48 +08:00

123 lines
3.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Swagger API 生成说明
## 方案选择
根据项目架构BFF层Gin + 微服务gRPC推荐使用 **grpc-gateway** 方案:
1. ✅ 自动从proto生成REST API代码
2. ✅ 自动生成Swagger/OpenAPI文档
3. ✅ 保持proto和REST API的一致性
4. ✅ 支持同时提供gRPC和REST两种接口
## 方案对比
| 方案 | 优点 | 缺点 | 适用场景 |
|------|------|------|---------|
| **grpc-gateway** | 自动生成、一致性高 | 需要在proto中添加注解 | ✅ **推荐**需要同时支持gRPC和REST |
| 手动编写Swagger | 灵活性高 | 工作量大、易不一致 | 接口差异大时 |
| protoc-gen-openapiv2 | 直接生成OpenAPI | 不能生成REST API代码 | 只需要文档时 |
## 安装依赖
### 1. 安装 Protocol Buffers 编译器
```bash
# macOS
brew install protobuf
# 或下载预编译版本
# https://github.com/protocolbuffers/protobuf/releases
```
### 2. 安装 Go 插件
```bash
# grpc-gateway 相关插件
go install github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway@latest
go install github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2@latest
# 标准 proto 插件
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
```
### 3. 安装 Swagger UI可选用于查看文档
```bash
# 方式1使用 Docker
docker run -p 8080:8080 -e SWAGGER_JSON=/foo/swagger.json -v $(pwd)/swagger:/foo swaggerapi/swagger-ui
# 方式2使用 npm
npm install -g swagger-ui-serve
```
## 使用步骤
### 步骤1在proto文件中添加REST API注解
需要在proto文件中添加 `google/api/annotations.proto` 的注解:
```protobuf
import "google/api/annotations.proto";
service UserSocialService {
rpc Login(LoginRequest) returns (LoginResponse) {
option (google.api.http) = {
post: "/api/v1/auth/login"
body: "*"
};
}
rpc GetUser(GetUserRequest) returns (GetUserResponse) {
option (google.api.http) = {
get: "/api/v1/users/{user_id}"
};
}
}
```
### 步骤2生成代码和Swagger
运行 Makefile 中的命令:
```bash
make swagger # 生成REST API代码和Swagger文档
```
### 步骤3在Gin中使用生成的代码
生成的代码可以直接在Gin中注册路由。
## 目录结构
```
top-fans/
├── proto/ # Proto定义文件
├── swagger/ # Swagger相关文件
│ ├── swagger.json # 生成的Swagger JSON自动生成
│ ├── swagger.yaml # 生成的Swagger YAML自动生成
│ └── README.md # 本文档
├── api/ # 生成的REST API代码自动生成
│ └── gateway/ # grpc-gateway生成的代码
└── Makefile # 包含生成命令
```
## 注意事项
1. **Proto和REST API的关系**
- Proto定义是"源"REST API是"派生"
- 修改接口时先改proto再重新生成
2. **路径设计**
- REST API路径应遵循RESTful规范
- 与proto的RPC方法名可以不同
3. **认证方式**
- REST API使用Bearer TokenJWT
- 在Swagger中配置Security Scheme
4. **错误处理**
- gRPC错误码需要映射到HTTP状态码
- 使用grpc-gateway的默认映射或自定义