Skip to content

Commit

Permalink
feat(openapi): 添加对 openapi 结构体标签的支持
Browse files Browse the repository at this point in the history
  • Loading branch information
caixw committed Nov 22, 2024
1 parent 373a66d commit d70b3fb
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 7 deletions.
5 changes: 5 additions & 0 deletions openapi/openapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
29 changes: 25 additions & 4 deletions openapi/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package openapi

import (
"reflect"
"strings"
"time"

orderedmap "github.com/wk8/go-ordered-map/v2"
Expand Down Expand Up @@ -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
}
}
Expand Down
12 changes: 9 additions & 3 deletions openapi/schema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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).
Expand Down

0 comments on commit d70b3fb

Please sign in to comment.