Golang 结构到 Json 模式

Ant*_*nin 6 go jsonschema swagger openapi

您好,我需要从结构推断 json 架构 (github.com/go-openapi/spec.Schema):

type Testcase struct {
    Id           string    `json:"id,omitempty"`            // id of this test case
    Name         string    `json:"name,omitempty"`          // name of this test case
    CreationDate time.Time `json:"creation_date,omitempty"` // timestamp when the scenario was first created
    UpdateDate   time.Time `json:"update_date,omitempty"`   // last update timestamp
    Steps        []Step    `json:"steps,omitempty"`         // list of steps  type:"[]StepCcs"
}
Run Code Online (Sandbox Code Playgroud)

我找不到简单的方法来做到这一点。我想这是许多从代码生成开放 API 规范的 REST 框架的先决条件。

有人可以向我指出包含此类助手的包吗:即

func toSchema(obj interface{}) (spec.Schema, error)
Run Code Online (Sandbox Code Playgroud)

小智 6

https://github.com/invopop/jsonschema

就是您正在寻找的。

type TestUser struct {
  ID            int                    `json:"id"`
  Name          string                 `json:"name" jsonschema:"title=the name,description=The name of a friend,example=joe,example=lucy,default=alex"`
  Friends       []int                  `json:"friends,omitempty" jsonschema_description:"The list of IDs, omitted when empty"`
  Tags          map[string]interface{} `json:"tags,omitempty" jsonschema_extras:"a=b,foo=bar,foo=bar1"`
  BirthDate     time.Time              `json:"birth_date,omitempty" jsonschema:"oneof_required=date"`
  YearOfBirth   string                 `json:"year_of_birth,omitempty" jsonschema:"oneof_required=year"`
  Metadata      interface{}            `json:"metadata,omitempty" jsonschema:"oneof_type=string;array"`
  FavColor      string                 `json:"fav_color,omitempty" jsonschema:"enum=red,enum=green,enum=blue"`
}
Run Code Online (Sandbox Code Playgroud)

结果如下 JSON 架构:

jsonschema.Reflect(&TestUser{})
Run Code Online (Sandbox Code Playgroud)