从已注册 Controller 的 Form、返回类型及字段声明生成请求、 响应和校验约束,补充显式安全方案与操作级覆盖。 复用 kin-openapi 原生类型与校验,保留合并绑定语义, 为原生路由和无法等价映射的声明提供补充入口。 同步接入指南、迁移边界和可独立运行的契约导出示例。 验证:make verify、make race-check 及实际示例导出通过。
This commit is contained in:
1 parent
e901a1e964
commit
b4a21f53ac
13 files changed
+1304
-8
No files matched your search
@@ -0,0 +1,390 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/getkin/kin-openapi/openapi3"
|
||||
"github.com/getkin/kin-openapi/openapi3gen"
|
||||
)
|
||||
|
||||
var (
|
||||
contractEnumTokens = regexp.MustCompile(`'[^']*'|\S+`)
|
||||
jsonMarshalerType = reflect.TypeOf((*json.Marshaler)(nil)).Elem()
|
||||
)
|
||||
|
||||
// contractSchema 复用原生类型生成器,只补充 dc 和 binding 的静态语义。
|
||||
// 入参:t 为 DTO 类型,schemas 为本次生成拥有的组件集合;返回 Schema 或不支持的类型错误。
|
||||
func contractSchema(t reflect.Type, schemas openapi3.Schemas) (*openapi3.SchemaRef, error) {
|
||||
return filteredContractSchema(t, schemas, nil, false)
|
||||
}
|
||||
|
||||
// responseContractSchema 按序列化存在性生成响应,不将输入 binding 当作响应校验。
|
||||
// 入参:t 为响应类型,schemas 为组件集合;返回独立响应结构或类型错误。
|
||||
func responseContractSchema(t reflect.Type, schemas openapi3.Schemas) (*openapi3.SchemaRef, error) {
|
||||
return filteredContractSchema(t, schemas, nil, true)
|
||||
}
|
||||
|
||||
// filteredContractSchema 在生成根节点时排除可信注入属性,循环引用的组件也保留相同边界。
|
||||
// 入参:t 为 DTO,schemas 为组件集合,hidden 为根节点隐藏字段,response 为响应方向。
|
||||
// 返回:与运行时 JSON 序列化对应的结构或错误,不保留输入对象。
|
||||
func filteredContractSchema(t reflect.Type, schemas openapi3.Schemas, hidden map[string]bool, response bool) (*openapi3.SchemaRef, error) {
|
||||
if err := checkContractReferenceTypes(t, map[reflect.Type]bool{}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if t.Kind() == reflect.Interface {
|
||||
return openapi3.NewSchema().WithNullable().NewRef(), nil
|
||||
}
|
||||
local := openapi3.Schemas{}
|
||||
customizer := contractCustomizer(response)
|
||||
ref, err := openapi3gen.NewSchemaRefForValue(reflect.New(t).Elem().Interface(), local,
|
||||
openapi3gen.UseAllExportedFields(), openapi3gen.CreateFieldNameGenerator(func(field reflect.StructField, _ string) string { return contractFieldName(field, "json") }), openapi3gen.SchemaCustomizer(func(name string, t reflect.Type, tag reflect.StructTag, schema *openapi3.Schema) error {
|
||||
if err := customizer(name, t, tag, schema); err != nil {
|
||||
return err
|
||||
}
|
||||
if name == "_root" {
|
||||
for key := range hidden {
|
||||
delete(schema.Properties, key)
|
||||
}
|
||||
required := []string{}
|
||||
for _, key := range schema.Required {
|
||||
if !hidden[key] {
|
||||
required = append(required, key)
|
||||
}
|
||||
}
|
||||
schema.Required = required
|
||||
}
|
||||
return nil
|
||||
}))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ref == nil {
|
||||
return nil, fmt.Errorf("unsupported contract type %s", t)
|
||||
}
|
||||
for name, component := range local {
|
||||
if previous := schemas[name]; previous != nil {
|
||||
left, leftErr := json.Marshal(previous)
|
||||
right, rightErr := json.Marshal(component)
|
||||
if leftErr != nil || rightErr != nil || !bytes.Equal(left, right) {
|
||||
return nil, fmt.Errorf("conflicting recursive schema name %q", name)
|
||||
}
|
||||
}
|
||||
schemas[name] = component
|
||||
}
|
||||
if ref.Value != nil && (t.Kind() == reflect.Ptr || t.Kind() == reflect.Map || t.Kind() == reflect.Slice) {
|
||||
copy := *ref.Value
|
||||
ref.Value = ©
|
||||
ref.Value.Nullable = true
|
||||
}
|
||||
return ref, nil
|
||||
}
|
||||
|
||||
// checkContractReferenceTypes 拒绝原生生成器会作为结构体 Ref 对象处理的标量别名。
|
||||
// 入参:t 为 DTO 图类型,visited 防止循环重复;返回明确的不支持错误,避免依赖反射 panic。
|
||||
func checkContractReferenceTypes(t reflect.Type, visited map[reflect.Type]bool) error {
|
||||
if visited[t] {
|
||||
return nil
|
||||
}
|
||||
visited[t] = true
|
||||
if t.Kind() != reflect.Struct && strings.HasSuffix(t.Name(), "Ref") {
|
||||
return fmt.Errorf("non-struct reference-named DTO type %s requires a plain contract type", t)
|
||||
}
|
||||
if t.Implements(jsonMarshalerType) || reflect.PointerTo(t).Implements(jsonMarshalerType) {
|
||||
return nil
|
||||
}
|
||||
switch t.Kind() {
|
||||
case reflect.Ptr, reflect.Slice, reflect.Array, reflect.Map:
|
||||
return checkContractReferenceTypes(t.Elem(), visited)
|
||||
case reflect.Struct:
|
||||
for index := 0; index < t.NumField(); index++ {
|
||||
field := t.Field(index)
|
||||
if field.PkgPath != "" && !field.Anonymous || strings.SplitN(field.Tag.Get("json"), ",", 2)[0] == "-" {
|
||||
continue
|
||||
}
|
||||
if err := checkContractReferenceTypes(field.Type, visited); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// contractCustomizer 按方向补充字段语义,防止切片 tag 错误应用到元素。
|
||||
// 入参:response 表示响应序列化方向;返回原生回调,Meta 被排除、复杂序列化被标记。
|
||||
func contractCustomizer(response bool) openapi3gen.SchemaCustomizerFn {
|
||||
return func(name string, t reflect.Type, tag reflect.StructTag, schema *openapi3.Schema) error {
|
||||
if t == reflect.TypeOf(Meta{}) {
|
||||
return &openapi3gen.ExcludeSchemaSentinel{}
|
||||
}
|
||||
if t != reflect.TypeOf(time.Time{}) && (t.Implements(jsonMarshalerType) || reflect.PointerTo(t).Implements(jsonMarshalerType)) {
|
||||
*schema = openapi3.Schema{Extensions: map[string]any{"x-gin-custom-json": true}}
|
||||
return nil
|
||||
}
|
||||
if t.Kind() == reflect.Slice || t.Kind() == reflect.Map {
|
||||
schema.Nullable = true
|
||||
}
|
||||
if t.Kind() == reflect.Array {
|
||||
schema.Extensions = map[string]any{"x-gin-schema-unresolved": "fixed array; application schema required"}
|
||||
}
|
||||
if t.Kind() != reflect.Struct || !schema.Type.Is("object") {
|
||||
return nil
|
||||
}
|
||||
for _, field := range reflect.VisibleFields(t) {
|
||||
if field.PkgPath != "" || field.Type == reflect.TypeOf(Meta{}) {
|
||||
continue
|
||||
}
|
||||
label := contractFieldName(field, "json")
|
||||
property := schema.Properties[label]
|
||||
if property == nil || property.Value == nil {
|
||||
continue
|
||||
}
|
||||
property = nullableContractRef(field.Type, property)
|
||||
schema.Properties[label] = property
|
||||
property.Value.Description = field.Tag.Get("dc")
|
||||
binding := field.Tag.Get("binding")
|
||||
if !response && requiredContractField(field) || response && responseFieldRequired(t, field) {
|
||||
schema.Required = append(schema.Required, label)
|
||||
}
|
||||
valueType := field.Type
|
||||
for valueType.Kind() == reflect.Ptr {
|
||||
valueType = valueType.Elem()
|
||||
}
|
||||
quotedScalar := valueType.Kind() == reflect.Bool || valueType.Kind() >= reflect.Int && valueType.Kind() <= reflect.Float64 || valueType.Kind() == reflect.String
|
||||
if quotedScalar && property.Value.Extensions["x-gin-custom-json"] != true && strings.Contains(","+field.Tag.Get("json")+",", ",string,") {
|
||||
nullable := property.Value.Nullable
|
||||
property.Value = openapi3.NewStringSchema()
|
||||
property.Value.Nullable = nullable
|
||||
property.Value.Description = field.Tag.Get("dc")
|
||||
if !response {
|
||||
property.Value.Extensions = map[string]any{"x-gin-binding": binding}
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !response {
|
||||
applyContractRules(property.Value, binding)
|
||||
setContractDefault(property.Value, field.Tag)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// nullableContractRef 保留循环引用处的指针/集合可空语义,不把可空标志污染到共享组件。
|
||||
// 入参:t 为原字段类型,ref 为生成引用;返回允许必要 null 值的引用。
|
||||
func nullableContractRef(t reflect.Type, ref *openapi3.SchemaRef) *openapi3.SchemaRef {
|
||||
if t.Kind() == reflect.Ptr {
|
||||
if strings.HasPrefix(ref.Ref, "#/components/schemas/") {
|
||||
null := openapi3.NewObjectSchema().WithNullable()
|
||||
null.Enum = []any{nil}
|
||||
return &openapi3.SchemaRef{Value: &openapi3.Schema{AnyOf: openapi3.SchemaRefs{ref, null.NewRef()}}}
|
||||
}
|
||||
t = t.Elem()
|
||||
}
|
||||
if ref.Value == nil {
|
||||
return ref
|
||||
}
|
||||
if (t.Kind() == reflect.Slice || t.Kind() == reflect.Array) && ref.Value.Items != nil {
|
||||
ref.Value.Items = nullableContractRef(t.Elem(), ref.Value.Items)
|
||||
}
|
||||
if t.Kind() == reflect.Map && ref.Value.AdditionalProperties.Schema != nil {
|
||||
ref.Value.AdditionalProperties.Schema = nullableContractRef(t.Elem(), ref.Value.AdditionalProperties.Schema)
|
||||
}
|
||||
return ref
|
||||
}
|
||||
|
||||
// responseFieldRequired 只标记不会被 omitempty/omitzero 或匿名指针父级省略的字段。
|
||||
// 入参:root 为所属结构,field 为可见字段;返回是否保证存在对应 JSON 属性。
|
||||
func responseFieldRequired(root reflect.Type, field reflect.StructField) bool {
|
||||
tag := "," + field.Tag.Get("json") + ","
|
||||
if strings.Contains(tag, ",omitempty,") || strings.Contains(tag, ",omitzero,") {
|
||||
return false
|
||||
}
|
||||
for _, index := range field.Index[:len(field.Index)-1] {
|
||||
root = root.Field(index).Type
|
||||
if root.Kind() == reflect.Ptr {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// contractFieldName 返回指定绑定方式的静态字段名;入参为字段和 tag,- 表示隐藏。
|
||||
func contractFieldName(field reflect.StructField, tag string) string {
|
||||
name := strings.SplitN(field.Tag.Get(tag), ",", 2)[0]
|
||||
if name == "" {
|
||||
return field.Name
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
// requiredContractField 仅将无默认值的无条件 required 映射为存在性约束。
|
||||
// 入参:field 为字段声明;返回是否具有可直接表达的必填规则,零值检查仍由 binding 负责。
|
||||
func requiredContractField(field reflect.StructField) bool {
|
||||
if _, hasDefault := field.Tag.Lookup("default"); hasDefault {
|
||||
return false
|
||||
}
|
||||
binding := field.Tag.Get("binding")
|
||||
if strings.Contains(binding, "|") || strings.Contains(","+binding+",", ",omitempty,") || strings.Contains(","+binding+",", ",omitnil,") {
|
||||
return false
|
||||
}
|
||||
for _, rule := range strings.Split(field.Tag.Get("binding"), ",") {
|
||||
if rule == "required" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// applyContractRules 将可等价表达的单字段规则映射为标准关键字,其余保留原始扩展。
|
||||
// 入参:schema 为字段 Schema,binding 为声明;不修改 DTO,不注册运行时规则。
|
||||
func applyContractRules(schema *openapi3.Schema, binding string) {
|
||||
if binding == "" || binding == "-" {
|
||||
return
|
||||
}
|
||||
if schema.Extensions == nil {
|
||||
schema.Extensions = map[string]any{}
|
||||
}
|
||||
schema.Extensions["x-gin-binding"] = binding
|
||||
if schema.Format == "byte" || schema.Format == "binary" {
|
||||
return
|
||||
}
|
||||
// OR 和 omitempty 具有分支语义,不能静默转换成多个 AND 约束。
|
||||
if strings.Contains(binding, "|") || strings.Contains(","+binding+",", ",omitempty,") || strings.Contains(","+binding+",", ",omitnil,") {
|
||||
return
|
||||
}
|
||||
rules := strings.Split(binding, ",")
|
||||
for index, rule := range rules {
|
||||
if rule == "dive" {
|
||||
if schema.Items != nil && schema.Items.Value != nil {
|
||||
applyContractRules(schema.Items.Value, strings.Join(rules[index+1:], ","))
|
||||
}
|
||||
// Map 的 keys/endkeys 不能当作值约束;完整规则已在扩展中保留。
|
||||
return
|
||||
}
|
||||
key, value, _ := strings.Cut(rule, "=")
|
||||
switch key {
|
||||
case "email":
|
||||
if schema.Type.Is("string") {
|
||||
schema.Format = "email"
|
||||
}
|
||||
case "uuid", "uuid3", "uuid4", "uuid5":
|
||||
if schema.Type.Is("string") {
|
||||
schema.Format = "uuid"
|
||||
}
|
||||
case "oneof":
|
||||
values := []any{}
|
||||
for _, token := range contractEnumTokens.FindAllString(value, -1) {
|
||||
token = strings.Trim(token, "'")
|
||||
var (
|
||||
entry any = token
|
||||
err error
|
||||
)
|
||||
if schema.Type.Is("integer") {
|
||||
if strings.HasPrefix(token, "-") {
|
||||
entry, err = strconv.ParseInt(token, 10, 64)
|
||||
} else {
|
||||
entry, err = strconv.ParseUint(token, 10, 64)
|
||||
}
|
||||
} else if schema.Type.Is("number") {
|
||||
entry, err = strconv.ParseFloat(token, 64)
|
||||
}
|
||||
if err != nil {
|
||||
values = nil
|
||||
break
|
||||
}
|
||||
values = append(values, entry)
|
||||
}
|
||||
schema.Enum = values
|
||||
case "min", "max", "len", "gte", "lte", "gt", "lt":
|
||||
applyContractBound(schema, key, value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// applyContractBound 按值类型区分数值、长度、集合及 Map 大小。
|
||||
// 入参:schema 为字段结构,rule/value 为服务端规则;无法静态映射时仅保留 binding 扩展。
|
||||
func applyContractBound(schema *openapi3.Schema, rule string, value string) {
|
||||
if schema.Type.Is("integer") || schema.Type.Is("number") {
|
||||
number, err := strconv.ParseFloat(value, 64)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
switch rule {
|
||||
case "min", "gte":
|
||||
schema.WithMin(number)
|
||||
case "max", "lte":
|
||||
schema.WithMax(number)
|
||||
case "len":
|
||||
schema.WithMin(number).WithMax(number)
|
||||
case "gt":
|
||||
schema.WithMin(number).WithExclusiveMin(true)
|
||||
case "lt":
|
||||
schema.WithMax(number).WithExclusiveMax(true)
|
||||
}
|
||||
return
|
||||
}
|
||||
length, err := strconv.ParseUint(value, 10, 64)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
minimum, maximum := rule == "min" || rule == "gte" || rule == "len", rule == "max" || rule == "lte" || rule == "len"
|
||||
if rule == "gt" && length < ^uint64(0) {
|
||||
minimum = true
|
||||
length++
|
||||
}
|
||||
if rule == "lt" && length > 0 {
|
||||
maximum = true
|
||||
length--
|
||||
}
|
||||
switch {
|
||||
case schema.Type.Is("string"):
|
||||
if minimum {
|
||||
schema.MinLength = length
|
||||
}
|
||||
if maximum {
|
||||
schema.MaxLength = &length
|
||||
}
|
||||
case schema.Type.Is("array"):
|
||||
if minimum {
|
||||
schema.MinItems = length
|
||||
}
|
||||
if maximum {
|
||||
schema.MaxItems = &length
|
||||
}
|
||||
case schema.Type.Is("object"):
|
||||
if minimum {
|
||||
schema.MinProps = length
|
||||
}
|
||||
if maximum {
|
||||
schema.MaxProps = &length
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// setContractDefault 只记录可安全按 JSON 标量表示的静态 default 声明。
|
||||
// 入参:schema 为当前字段,tag 为声明;复杂类型默认值由应用补充,不执行反射赋值。
|
||||
func setContractDefault(schema *openapi3.Schema, tag reflect.StructTag) {
|
||||
value, exists := tag.Lookup("default")
|
||||
if !exists {
|
||||
return
|
||||
}
|
||||
if schema.Type.Is("string") {
|
||||
schema.Default = value
|
||||
return
|
||||
}
|
||||
if schema.Type.Is("integer") || schema.Type.Is("number") || schema.Type.Is("boolean") {
|
||||
var (
|
||||
decoded any
|
||||
)
|
||||
if json.Unmarshal([]byte(value), &decoded) == nil {
|
||||
schema.Default = decoded
|
||||
}
|
||||
}
|
||||
}
|
||||