从已注册 Controller 的 Form、返回类型及字段声明生成请求、 响应和校验约束,补充显式安全方案与操作级覆盖。 复用 kin-openapi 原生类型与校验,保留合并绑定语义, 为原生路由和无法等价映射的声明提供补充入口。 同步接入指南、迁移边界和可独立运行的契约导出示例。 验证:make verify、make race-check 及实际示例导出通过。
This commit is contained in:
1 parent
e901a1e964
commit
b4a21f53ac
13 files changed
+1304
-8
No files matched your search
@@ -0,0 +1,76 @@
|
||||
// Command openapi 在不启动 HTTP 服务的情况下导出示例契约。
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"os"
|
||||
|
||||
"git.zhangdeman.cn/github/ginframework/fault"
|
||||
framework "git.zhangdeman.cn/github/ginframework/http"
|
||||
"git.zhangdeman.cn/github/ginframework/logger"
|
||||
"github.com/getkin/kin-openapi/openapi3"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
codeExportJSON = 990201
|
||||
codeExportFile = 990202
|
||||
)
|
||||
|
||||
type itemForm struct {
|
||||
framework.Meta `path:"/items/:id" method:"GET" summary:"获取条目" tag:"items" security:"bearer" dc:"纯文档安全声明;本示例仅导出,不启动业务服务"`
|
||||
ID int64 `json:"-" uri:"id" binding:"required,min=1" dc:"条目标识"`
|
||||
}
|
||||
|
||||
type itemOutput struct {
|
||||
ID int64 `json:"id" dc:"条目标识"`
|
||||
Name string `json:"name" dc:"展示名称"`
|
||||
}
|
||||
|
||||
type items struct{}
|
||||
|
||||
// Get 声明可由反射读取的公开响应;文档生成不会调用该方法。
|
||||
// 入参:ctx 为业务请求,input 为表单;返回示例 DTO 和错误。
|
||||
func (*items) Get(ctx *gin.Context, input *itemForm) (*itemOutput, error) {
|
||||
return &itemOutput{ID: input.ID, Name: "example"}, nil
|
||||
}
|
||||
|
||||
// main 显式选择输出路径;生成失败时保留源头日志并设置非零退出码。
|
||||
func main() {
|
||||
output := flag.String("out", "openapi.json", "生成文档的输出文件")
|
||||
flag.Parse()
|
||||
if err := export(*output); err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// export 只装配静态路由和文档,不监听端口;入参为输出路径,返回已记录的错误。
|
||||
func export(path string) error {
|
||||
server, err := framework.NewServer(framework.Config{}, framework.Options{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err = server.Group("/api", nil, &items{}); err != nil {
|
||||
return err
|
||||
}
|
||||
doc, err := server.OpenAPI(framework.OpenAPIOptions{
|
||||
Title: "Ginframework example", Version: "1.0.0",
|
||||
SecuritySchemes: openapi3.SecuritySchemes{"bearer": &openapi3.SecuritySchemeRef{Value: &openapi3.SecurityScheme{Type: "http", Scheme: "bearer", BearerFormat: "JWT"}}},
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
raw, err := json.MarshalIndent(doc, "", " ")
|
||||
if err != nil {
|
||||
classified := fault.New(codeExportJSON, "encode exported OpenAPI document failed", err)
|
||||
logger.RecordError("encode exported OpenAPI document failed", classified)
|
||||
return classified
|
||||
}
|
||||
if err = os.WriteFile(path, raw, 0600); err != nil {
|
||||
classified := fault.New(codeExportFile, "write exported OpenAPI document failed", err)
|
||||
logger.RecordError("write exported OpenAPI document failed", classified)
|
||||
return classified
|
||||
}
|
||||
return nil
|
||||
}
|
||||