如何将Golang结构体转换为github.com/go-openapi/spec.Schema格式JSON Schema
解决方案
你要的能力go-openapi官方生态已经提供了现成实现,不需要自己手写反射逻辑:
1. 所需依赖
直接安装官方提供的反射工具包:
go get github.com/go-openapi/reflector github.com/go-openapi/strfmt
2. 实现你要的toSchema函数
import ( "github.com/go-openapi/reflector" "github.com/go-openapi/spec" "github.com/go-openapi/strfmt" ) func toSchema(obj interface{}) (spec.Schema, error) { // 初始化反射器,使用默认的格式注册表(内置支持time.Time、常见格式的自动映射) reflectorInstance := reflector.NewReflector(strfmt.Default) schemaPtr, err := reflectorInstance.Reflect(obj) if err != nil { return spec.Schema{}, err } return *schemaPtr, nil }
3. 适配Testcase结构体的说明
- 该工具会自动识别
json标签的字段名、omitempty属性,自动标记非必填字段 time.Time类型会自动映射为type: string, format: date-time的标准OpenAPI格式- 嵌套结构体、切片类型会自动递归生成对应schema
- 如果需要自定义字段描述、类型覆盖,可以给结构体加
swagger标签,示例如下:
生成的schema会自动把标签里的描述、类型覆盖填入对应字段。type Testcase struct { Id string `json:"id,omitempty" swagger:"description=id of this test case"` Name string `json:"name,omitempty" swagger:"description=name of this test case"` CreationDate time.Time `json:"creation_date,omitempty" swagger:"description=timestamp when the scenario was first created"` UpdateDate time.Time `json:"update_date,omitempty" swagger:"description=last update timestamp"` Steps []Step `json:"steps,omitempty" swagger:"description=list of steps,type=[]StepCcs"` }
内容的提问来源于stack exchange,提问作者Antonin
相关产品推荐
相关产品推荐

