From 4f707550ba749f50a859f0ece1f0bd6f931193e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Sat, 28 Nov 2026 01:47:41 -0800 Subject: [PATCH] =?UTF-8?q?fix(openapi):=20=E9=9A=94=E7=A6=BB=E4=B8=8D?= =?UTF-8?q?=E5=90=8C=E6=A0=B9=E5=A5=91=E7=BA=A6=E7=9A=84=E9=80=92=E5=BD=92?= =?UTF-8?q?=E7=BB=84=E4=BB=B6=E5=BC=95=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/getting-started.md | 2 +- http/openapi_schema.go | 48 +++++++++++++++++++++++++++++++++++++++++ http/openapi_test.go | 46 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 95 insertions(+), 1 deletion(-) diff --git a/docs/getting-started.md b/docs/getting-started.md index ac1987c..c016913 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -221,7 +221,7 @@ go run ./examples/openapi -out /tmp/ginframework-openapi.json 合并来源的语义:GET/HEAD/OPTIONS 只生成路径与查询;有 Body 的方法同时生成可选查询和可选 RequestBody。必填发生在合并、默认值、可信注入之后,因此根 Body 不使用会误拒绝其他来源的 required,而用 `x-gin-required-after-merge` 保留无条件必填清单。普通查询中带 default 的字段不强制出现。JSON Schema 的 required 只表达存在性,不能替代 validator 对零值的检查。 -所有非空 binding 声明保留在 `x-gin-binding`。跨字段、自定义、OR、omitempty/omitnil 等规则不冒充等价的标准约束;Map keys/endkeys 的值规则也不自动推断。复杂场景以运行时校验为准,并由应用通过 Customize 补充。固定长度 Go 数组标记 `x-gin-schema-unresolved`;自定义 JSON 序列化类型标记 `x-gin-custom-json`,其形状不自动推断。any 保持开放结构。循环组件同名但定义不一致时明确失败,需使用不同 DTO 名称。没有完整未知字段、字段存在性或自定义序列化分析器。 +所有非空 binding 声明保留在 `x-gin-binding`。跨字段、自定义、OR、omitempty/omitnil 等规则不冒充等价的标准约束;Map keys/endkeys 的值规则也不自动推断。复杂场景以运行时校验为准,并由应用通过 Customize 补充。固定长度 Go 数组标记 `x-gin-schema-unresolved`;自定义 JSON 序列化类型标记 `x-gin-custom-json`,其形状不自动推断。any 保持开放结构。循环组件按根契约、输入输出方向和可信字段集合生成独立的稳定名称,同一递归 DTO 在不同嵌入上下文中不会互相覆盖。单个根契约内部仍不支持不同包中同名且定义不同的递归 DTO;此时需使用不同 DTO 名称。没有完整未知字段、字段存在性或自定义序列化分析器。 当前原生类型生成器不支持名称以 Ref 结尾的非结构体别名;框架会返回明确错误,避免反射 panic。此类字段先转换为普通标量对外 DTO。响应侧只推导序列化结构与属性存在性,不把输入 binding 标签当作已经执行的输出校验。 diff --git a/http/openapi_schema.go b/http/openapi_schema.go index a6043f9..dd4122d 100644 --- a/http/openapi_schema.go +++ b/http/openapi_schema.go @@ -2,6 +2,7 @@ package http import ( "bytes" + "crypto/sha256" "encoding/json" "fmt" "reflect" @@ -68,6 +69,23 @@ func filteredContractSchema(t reflect.Type, schemas openapi3.Schemas, hidden map if ref == nil { return nil, fmt.Errorf("unsupported contract type %s", t) } + // 递归组件按根契约隔离,避免不同方向或嵌入上下文产生同名不同定义。 + namespace := fmt.Sprintf("%s/%s/%t/%v", t.PkgPath(), t, response, hidden) + names := map[string]string{} + for name := range local { + identity := sha256.Sum256([]byte(namespace + "/" + name)) + names[name] = fmt.Sprintf("Schema_%x", identity[:16]) + } + visited := map[*openapi3.Schema]bool{} + renameContractReferences(ref, names, visited) + for _, component := range local { + renameContractReferences(component, names, visited) + } + renamed := openapi3.Schemas{} + for name, component := range local { + renamed[names[name]] = component + } + local = renamed for name, component := range local { if previous := schemas[name]; previous != nil { left, leftErr := json.Marshal(previous) @@ -388,3 +406,33 @@ func setContractDefault(schema *openapi3.Schema, tag reflect.StructTag) { } } } + +// renameContractReferences 只重命名本次生成的循环引用,保持原生生成器的内联和可空语义。 +// 入参:ref 为当前节点,names 为本地名称映射,visited 防止共享图重复遍历。 +func renameContractReferences(ref *openapi3.SchemaRef, names map[string]string, visited map[*openapi3.Schema]bool) { + if ref == nil { + return + } + const prefix = "#/components/schemas/" + if strings.HasPrefix(ref.Ref, prefix) { + if name, exists := names[strings.TrimPrefix(ref.Ref, prefix)]; exists { + ref.Ref = prefix + name + } + } + schema := ref.Value + if schema == nil || visited[schema] { + return + } + visited[schema] = true + for _, child := range schema.Properties { + renameContractReferences(child, names, visited) + } + for _, group := range []openapi3.SchemaRefs{schema.AllOf, schema.AnyOf, schema.OneOf} { + for _, child := range group { + renameContractReferences(child, names, visited) + } + } + for _, child := range []*openapi3.SchemaRef{schema.Not, schema.Items, schema.AdditionalProperties.Schema} { + renameContractReferences(child, names, visited) + } +} diff --git a/http/openapi_test.go b/http/openapi_test.go index 33b85ef..9856d78 100644 --- a/http/openapi_test.go +++ b/http/openapi_test.go @@ -319,3 +319,49 @@ func TestOpenAPIUnsupportedReferenceAliasReturnsError(t *testing.T) { t.Fatal("unsupported scalar Ref alias did not return an error") } } + +// 同一递归类型在根响应和匿名嵌入响应中会经过不同展开路径。 +type embeddedRecursiveOutput struct { + recursiveValue + Label string `json:"label"` +} +type recursiveBaseForm struct { + Meta `path:"/recursive/base" method:"GET"` +} +type recursiveExtendedForm struct { + Meta `path:"/recursive/extended" method:"GET"` +} +type embeddedRecursiveController struct{} + +func (*embeddedRecursiveController) Base(*gin.Context, *recursiveBaseForm) (recursiveValue, error) { + return recursiveValue{}, nil +} +func (*embeddedRecursiveController) Extended(*gin.Context, *recursiveExtendedForm) (embeddedRecursiveOutput, error) { + return embeddedRecursiveOutput{}, nil +} + +// TestOpenAPIRecursiveComponentsAreIsolatedByContract 验证同一递归类型的不同根契约互不污染。 +func TestOpenAPIRecursiveComponentsAreIsolatedByContract(t *testing.T) { + server, _ := NewServer(Config{}, Options{}) + if err := server.Group("", nil, &embeddedRecursiveController{}); err != nil { + t.Fatal(err) + } + doc, err := server.OpenAPI(OpenAPIOptions{Title: "Recursive variants", Version: "1"}) + if err != nil { + t.Fatal(err, errors.Unwrap(err)) + } + for _, path := range []string{"/recursive/base", "/recursive/extended"} { + recorder := httptest.NewRecorder() + server.Handler().ServeHTTP(recorder, httptest.NewRequest("GET", path, nil)) + var ( + actual any + ) + if err = json.Unmarshal(recorder.Body.Bytes(), &actual); err != nil { + t.Fatal(err) + } + schema := doc.Paths.Value(path).Get.Responses.Status(200).Value.Content["application/json"].Schema.Value + if err = schema.VisitJSON(actual); err != nil { + t.Fatalf("%s contract disagrees with wire JSON: %v", path, err) + } + } +}