Repository navigation
Description
Found while reviewing #2514. It's pre-existing on main, and independent of that PR.
Problem
Under schema-merging-behavior: v1 (or old-merge-schemas: true), an allOf member that is a $ref gets embedded in a struct, whatever its type:
type WrapName struct {
Name `yaml:",inline"` // Name = string
}encoding/json only flattens embedded structs. It encodes an embedded field of any other type as a regular field named after the type. So when the referenced schema isn't an object (untyped {}, a primitive, an array, or a map from additionalProperties), the value goes on the wire wrapped in an object keyed by the Go type name:
| member | v1 marshals as | expected | v1 unmarshals the expected value |
|---|---|---|---|
Untyped: {} |
{"Untyped":"x"} |
"x" |
error: cannot unmarshal string |
Name: {type: string} |
{"Name":"x"} |
"x" |
error: cannot unmarshal string |
Names: {type: array, items: {type: string}} |
{"Names":["a","b"]} |
["a","b"] |
error: cannot unmarshal array |
Labels: {type: object, additionalProperties: {type: string}} |
{"Labels":{"k":"v"}} |
{"k":"v"} |
no error, but Labels is left empty |
Obj: {type: object, properties: …} |
{"v":"x"} |
{"v":"x"} |
works |
This affects models, clients and servers alike, including strict-server responses. v2 and v3 are fine: they lower a single-member allOf to an alias (type WrapName = Name).
Reproduction
openapi: "3.0.3"
info: {title: t, version: "1"}
paths: {}
components:
schemas:
Name: {type: string}
WrapName:
allOf:
- $ref: '#/components/schemas/Name'Config: generate: {models: true}, output-options: {skip-prune: true}, compatibility: {schema-merging-behavior: v1}.
b, _ := json.Marshal(WrapName{Name: "x"})
fmt.Println(string(b)) // {"Name":"x"}, expected "x"
var w WrapName
err := json.Unmarshal([]byte(`"x"`), &w) // json: cannot unmarshal string into Go value of type WrapNameThe same happens for an allOf of an untyped $ref followed by sibling keywords (allOf: [{$ref: Untyped}, {description: …}]), and for a component that is itself such an allOf.
Notes
- One fix keeps v1's Go shape, so
WrapName{Name: "x"}still compiles: when every other member contributes no fields, generateMarshalJSON/UnmarshalJSONon the struct that delegate to the embedded non-object member. Switching those cases to an alias, as v2 does, would also fix the wire but would change the Go type. - The wire encoding has never matched the spec, so there's nothing to preserve there.
internal/test/servers/strict/responsebody_v1(added in the fix: handle untyped strict response bodies #2514 follow-up) records the current{"Untyped": …}encoding. Update it with the fix.
Activity
fix: lower a v1 allOf of a non-object $ref to the member's type
fix: lower a v1 allOf of a non-object $ref to the member's type (oapi…