diff --git a/openapi/openapi.go b/openapi/openapi.go index 26575494..d9e81d63 100644 --- a/openapi/openapi.go +++ b/openapi/openapi.go @@ -4,6 +4,11 @@ // Package openapi 采用 [web.Middleware] 中间件的形式生成 [openapi] 文档 // +// 结构体标签 +// +// - comment 用于可翻译的注释,该内容会被翻译后保存在字段的 Schema.Description 中; +// - openapi 对 openapi 类型的自定义,格式为 type,format,可以自定义字段的类型和格式; +// // [openapi]: https://spec.openapis.org/oas/v3.1.1.html package openapi diff --git a/openapi/schema.go b/openapi/schema.go index 33ab0a69..5c85a5c2 100644 --- a/openapi/schema.go +++ b/openapi/schema.go @@ -6,6 +6,7 @@ package openapi import ( "reflect" + "strings" "time" orderedmap "github.com/wk8/go-ordered-map/v2" @@ -189,17 +190,37 @@ func schemaFromObjectType(d *Document, t reflect.Type, isRoot bool, rootName str if comment != "" { itemDesc = web.Phrase(comment) } + + if tt := f.Tag.Get("openapi"); tt != "" { + if tt != "-" { + tags := strings.Split(tt, ",") + + format := "" + if len(tags) > 1 { + format = tags[1] + } + + s.Properties[name] = &Schema{ + Description: itemDesc, + Type: tags[0], + Format: format, + XML: xml, + } + } + continue + } + } - item := &Schema{Description: itemDesc} + item := &Schema{ + Description: itemDesc, + XML: xml, + } schemaFromType(d, t.Field(i).Type, false, rootName, item) if item.Type == "" { continue } - if xml != nil { - item.XML = xml - } s.Properties[name] = item } } diff --git a/openapi/schema_test.go b/openapi/schema_test.go index df25da2b..dc766d7c 100644 --- a/openapi/schema_test.go +++ b/openapi/schema_test.go @@ -18,6 +18,9 @@ type schemaObject1 struct { object Root string T time.Time + X string `openapi:"-"` + Y string `openapi:"integer"` + Z *object `openapi:"string,date"` } type schemaObject2 struct { @@ -56,16 +59,19 @@ func TestDocument_newSchema(t *testing.T) { s = d.newSchema(reflect.ValueOf(schemaObject1{}).Type()) a.Equal(s.Type, TypeObject). NotZero(s.Ref.Ref). - Length(s.Properties, 5). + Length(s.Properties, 7). Equal(s.Properties["id"].Type, TypeInteger). Equal(s.Properties["Root"].Type, TypeString). Equal(s.Properties["T"].Type, TypeString). - Equal(s.Properties["T"].Format, FormatDateTime) + Equal(s.Properties["T"].Format, FormatDateTime). + Equal(s.Properties["Y"].Type, TypeInteger). + Equal(s.Properties["Z"].Type, TypeString). + Equal(s.Properties["Z"].Format, FormatDate) s = d.newSchema(reflect.ValueOf(schemaObject2{}).Type()) a.Equal(s.Type, TypeObject). NotZero(s.Ref.Ref). - Length(s.Properties, 5). + Length(s.Properties, 7). Equal(s.Properties["id"].Type, TypeInteger). Equal(s.Properties["Root"].Type, TypeString). Equal(s.Properties["T"].Type, TypeString).