44 lines
1.4 KiB
Go
44 lines
1.4 KiB
Go
package routes
|
||
|
||
import (
|
||
"regexp"
|
||
|
||
"github.com/gofiber/fiber/v2"
|
||
|
||
"github.com/break/junhong_cmp_fiber/pkg/openapi"
|
||
)
|
||
|
||
// RouteSpec 定义接口文档元数据
|
||
type RouteSpec struct {
|
||
Summary string
|
||
Input interface{} // 请求参数结构体 (Query/Path/Body)
|
||
Output interface{} // 响应参数结构体
|
||
Tags []string
|
||
Auth bool // 是否需要认证图标 (预留)
|
||
}
|
||
|
||
// pathParamRegex 用于匹配 Fiber 的路径参数格式 /:param
|
||
var pathParamRegex = regexp.MustCompile(`/:([a-zA-Z0-9_]+)`)
|
||
|
||
// Register 封装后的注册函数
|
||
// router: Fiber 路由组
|
||
// doc: 文档生成器 (如果在运行 Web 服务时为 nil,在生成文档时为非 nil)
|
||
// basePath: 当前路由组的基础路径 (用于文档生成)
|
||
// method, path: HTTP 方法和路径
|
||
// handler: Fiber Handler
|
||
// spec: 文档元数据
|
||
func Register(router fiber.Router, doc *openapi.Generator, basePath, method, path string, handler fiber.Handler, spec RouteSpec) {
|
||
// 1. 注册实际的 Fiber 路由
|
||
router.Add(method, path, handler)
|
||
|
||
// 2. 注册文档 (如果 doc 不为空 - 也就是在生成文档模式下)
|
||
if doc != nil {
|
||
// 简单的路径拼接
|
||
fullPath := basePath + path
|
||
// 将 Fiber 路由参数格式 /:id 转换为 OpenAPI 格式 /{id}
|
||
openapiPath := pathParamRegex.ReplaceAllString(fullPath, "/{$1}")
|
||
|
||
doc.AddOperation(method, openapiPath, spec.Summary, spec.Input, spec.Output, spec.Tags...)
|
||
}
|
||
}
|