77 lines
2.5 KiB
Go
77 lines
2.5 KiB
Go
// Command openapi 在不启动 HTTP 服务的情况下导出示例契约。
|
|
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"flag"
|
|
"os"
|
|
|
|
"git.zhangdeman.cn/zhangdeman/ginframework/fault"
|
|
framework "git.zhangdeman.cn/zhangdeman/ginframework/http"
|
|
"git.zhangdeman.cn/zhangdeman/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
|
|
}
|