Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 41 additions & 2 deletions modules/openapi-generator/src/main/resources/go/client.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -191,10 +191,14 @@ func parameterAddToHeaderOrQuery(headerOrQueryParams interface{}, keyPrefix stri
for i:=0;i<lenIndValue;i++ {
var arrayValue = indValue.Index(i)
var keyPrefixForCollectionType = keyPrefix
var styleForElement = style
if style == "deepObject" {
keyPrefixForCollectionType = keyPrefix + "[" + strconv.Itoa(i) + "]"
} else if style == "form" {
// only the parameter's own map is flattened; a map inside an array keeps its bracketed path
styleForElement = ""
}
parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefixForCollectionType, arrayValue.Interface(), style, collectionType)
parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefixForCollectionType, arrayValue.Interface(), styleForElement, collectionType)
}
return

Expand All @@ -206,13 +210,36 @@ func parameterAddToHeaderOrQuery(headerOrQueryParams interface{}, keyPrefix stri
iter := indValue.MapRange()
for iter.Next() {
k,v := iter.Key(), iter.Value()
parameterAddToHeaderOrQuery(headerOrQueryParams, fmt.Sprintf("%s[%s]", keyPrefix, k.String()), v.Interface(), style, collectionType)
var keyPrefixForMapEntry = fmt.Sprintf("%s[%s]", keyPrefix, k.String())
var styleForMapEntry = style
if style == "form" {
// form style: one query parameter per entry, keyed by the property name; anything nested keeps its bracketed path
keyPrefixForMapEntry = k.String()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The if style == "form" branch explodes every form-style object to per-entry keys even when explode: false (e.g. flatFilter), because Go never passes explode to the runtime. This produces key=value entries for flatFilter instead of the single comma-joined flatFilter=key,value the new fixture documents. The new Go test checks only the call-string and not the wire output, so it does not catch the mismatch; either propagate explode into the runtime or make the test verify the actual serialized output.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At modules/openapi-generator/src/main/resources/go/client.mustache, line 214:

<comment>The `if style == "form"` branch explodes every form-style object to per-entry keys even when `explode: false` (e.g. flatFilter), because Go never passes `explode` to the runtime. This produces `key=value` entries for flatFilter instead of the single comma-joined `flatFilter=key,value` the new fixture documents. The new Go test checks only the call-string and not the wire output, so it does not catch the mismatch; either propagate explode into the runtime or make the test verify the actual serialized output.</comment>

<file context>
@@ -206,7 +206,14 @@ func parameterAddToHeaderOrQuery(headerOrQueryParams interface{}, keyPrefix stri
+						// form style explodes an object into one parameter per entry, keyed by the
+						// property name alone. Only deepObject nests the property under the
+						// parameter name.
+						keyPrefixForMapEntry = k.String()
+					}
+					parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefixForMapEntry, v.Interface(), style, collectionType)
</file context>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Known — this is the "Known gaps, called out deliberately" section of the description, and the same caveat is repeated in a comment in the go test.

The go templates pass only style to the runtime, never explode, so parameterAddToHeaderOrQuery genuinely cannot tell the two apart. For flatFilter the spec asks for flatFilter=category,books; go bracketed it (flatFilter[category]=books) before this change and explodes it (category=books) after. Both are wrong, so this is not a regression in correctness — but I agree it is not a fix either, which is why it is documented rather than claimed.

On the test: it asserts on the emitted source because there is no harness in the repo that exercises parameterAddToHeaderOrQuery at runtime — nothing under samples/**/*_test.go references it. Verifying actual wire output would mean adding that harness, which I am glad to do if it is wanted.

Plumbing explode properly changes parameterAddToHeaderOrQuery's signature and all 12 call sites in go/api.mustache. I offered that in the description and the offer stands — it just wants a maintainer's call, since it changes a runtime function signature that generated code has depended on for a long time.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two corrections: the explode: false caveat now lives only in the description (d5cf44b dropped the test comment), and TestQueryDeepObject in samples/openapi3/client/petstore/go/fake_api_test.go does exercise parameterAddToHeaderOrQuery at runtime; it just has no form-style map parameter to reach the new branch.

styleForMapEntry = ""
// a nil entry, or a nil item of a list entry, is left out rather than sent as "null"
entry, ok := parameterValueIndirect(v)
if !ok {
continue
}
if entry.Kind() == reflect.Slice {
for i := 0; i < entry.Len(); i++ {
if element, ok := parameterValueIndirect(entry.Index(i)); ok {
parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefixForMapEntry, element.Interface(), styleForMapEntry, collectionType)
}
}
continue
}
}
parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefixForMapEntry, v.Interface(), styleForMapEntry, collectionType)
}
return

case reflect.Interface:
fallthrough
case reflect.Ptr:
if v.IsNil() {
return
}
parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefix, v.Elem().Interface(), style, collectionType)
return

Expand Down Expand Up @@ -247,6 +274,18 @@ func parameterAddToHeaderOrQuery(headerOrQueryParams interface{}, keyPrefix stri
}
}

// parameterValueIndirect unwraps interfaces and pointers down to the value they hold,
// reporting false when that value is nil
func parameterValueIndirect(v reflect.Value) (reflect.Value, bool) {
for v.Kind() == reflect.Interface || v.Kind() == reflect.Ptr {
if v.IsNil() {
return v, false
}
v = v.Elem()
}
return v, v.IsValid()
}

// helper for converting interface{} parameters to json strings
func parameterToJson(obj interface{}) (string, error) {
jsonBuf, err := json.Marshal(obj)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,35 @@ public void testPrimitiveTypeInOneOf() throws IOException {
TestUtils.assertFileNotContains(modelFile, "dst.int32");
}

@Test(description = "Verify form style query parameters explode an object instead of bracketing it")
public void testExplodedObjectQueryParameter() throws IOException {
File output = Files.createTempDirectory("test").toFile();
output.deleteOnExit();

final CodegenConfigurator configurator = new CodegenConfigurator()
.setGeneratorName("go")
.setInputSpec("src/test/resources/3_0/exploded-object-query-param.yaml")
.setOutputDir(output.getAbsolutePath().replace("\\", "/"));

DefaultGenerator generator = new DefaultGenerator();
List<File> files = generator.opts(configurator.toClientOptInput()).generate();
files.forEach(File::deleteOnExit);

TestUtils.assertFileContains(Paths.get(output + "/client.go"),
"keyPrefixForMapEntry = k.String()",
"if !ok { continue } if entry.Kind() == reflect.Slice {",
"case reflect.Ptr: if v.IsNil() { return }",
"styleForElement = \"\"");

// the api passes the declared style through
Path api = Paths.get(output + "/api_default.go");
TestUtils.assertFileContains(api,
"parameterAddToHeaderOrQuery(localVarQueryParams, \"filter\", r.filter, \"form\", \"\")",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: These assertions expect the generated api_default.go to pass "form" to parameterAddToHeaderOrQuery for filter and typedFilter, but GoClientCodegen only sets codegenParameter.style when the OpenAPI document declares a style. The fixture leaves style unset for those two params (they default to form by spec, not by the codegen), so the generated calls carry an empty style ("", ""), as the regenerated sample does for every no-style query param (e.g. api_fake.go: "query", r.query, "", ""). The assertion won't match and the test fails. Because the new un-bracketing in go/client.mustache is gated on if style == "form", passing an empty style also means the runtime never explodes these default-style objects, so the fix wouldn't take effect for them either. Declare style: form explicitly on filter and typedFilter in the fixture (and regenerate), or pass the style through so the empty default becomes "form".

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoClientCodegenTest.java, line 172:

<comment>These assertions expect the generated api_default.go to pass "form" to parameterAddToHeaderOrQuery for filter and typedFilter, but GoClientCodegen only sets codegenParameter.style when the OpenAPI document declares a style. The fixture leaves style unset for those two params (they default to form by spec, not by the codegen), so the generated calls carry an empty style (`"", ""`), as the regenerated sample does for every no-style query param (e.g. api_fake.go: `"query", r.query, "", ""`). The assertion won't match and the test fails. Because the new un-bracketing in go/client.mustache is gated on `if style == "form"`, passing an empty style also means the runtime never explodes these default-style objects, so the fix wouldn't take effect for them either. Declare `style: form` explicitly on filter and typedFilter in the fixture (and regenerate), or pass the style through so the empty default becomes "form".</comment>

<file context>
@@ -141,6 +141,40 @@ public void testPrimitiveTypeInOneOf() throws IOException {
+        // of which differ from the comma joined pairs the specification asks for.
+        Path api = Paths.get(output + "/api_default.go");
+        TestUtils.assertFileContains(api,
+                "parameterAddToHeaderOrQuery(localVarQueryParams, \"filter\", r.filter, \"form\", \"\")",
+                "parameterAddToHeaderOrQuery(localVarQueryParams, \"typedFilter\", r.typedFilter, \"form\", \"\")",
+                "parameterAddToHeaderOrQuery(localVarQueryParams, \"deepFilter\", r.deepFilter, \"deepObject\", \"\")",
</file context>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not valid — the test passes.

[INFO] Tests run: 382, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

(GoClientCodegenTest, GoModelTest, GoClientOptionsTest, AbstractGoCodegenTest, PythonClientCodegenTest, PythonPydanticV1ClientCodegenTest, TypeScriptFetchClientCodegenTest, TypeScriptFetchModelTest, TypeScriptFetchClientOptionsTest, DefaultCodegenTest.)

The first step of the reasoning is right: DefaultCodegen.fromParameter only assigns codegenParameter.style inside if (parameter.getStyle() != null). The second step is where it goes wrong — swagger-parser has already applied the OpenAPI default by the time we get there, so getStyle() returns FORM for a query parameter that declares no style. It is never null, and the codegen does not need to supply the default itself.

The regenerated samples show it directly. testBodyWithQueryParams in petstore-with-fake-endpoints-models-for-testing.yaml:1095 declares no style:, and the generated client is:

parameterAddToHeaderOrQuery(localVarQueryParams, "query", r.query, "form", "")

not the "", "" this comment predicts — there is no ", "", "" anywhere in the go samples. So the fixture does not need an explicit style: form, and the runtime does explode these default-style objects.

"parameterAddToHeaderOrQuery(localVarQueryParams, \"typedFilter\", r.typedFilter, \"form\", \"\")",
"parameterAddToHeaderOrQuery(localVarQueryParams, \"deepFilter\", r.deepFilter, \"deepObject\", \"\")",
"parameterAddToHeaderOrQuery(localVarQueryParams, \"flatFilter\", r.flatFilter, \"form\", \"\")");
}

@Test
public void testNullableComposition() throws IOException {
File output = Files.createTempDirectory("test").toFile();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
openapi: 3.0.3
info:
title: Exploded object query parameters
description: >
Object typed query parameters under form/explode (as a free-form object and as a typed map), deepObject, and form without explode. The free-form variant matters because it is flagged isMap but not isContainer.
version: 1.0.0
servers:
- url: localhost:8080
paths:
/items:
get:
operationId: listItems
parameters:
# style and explode both left out, so the form/true defaults apply: every entry
# becomes its own parameter, keyed by the property name alone.
- in: query
name: filter
schema:
type: object
# the same, but declared as a map rather than as a free-form object
- in: query
name: typedFilter
schema:
type: object
additionalProperties:
type: string
# deepObject nests each entry under the parameter name: deepFilter[key]=value
- in: query
name: deepFilter
style: deepObject
explode: true
schema:
type: object
# form without explode keeps a single parameter carrying the whole object
- in: query
name: flatFilter
style: form
explode: false
schema:
type: object
responses:
'200':
description: a list of items
content:
application/json:
schema:
type: array
items:
type: string
43 changes: 41 additions & 2 deletions samples/client/echo_api/go-external-refs/client.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

43 changes: 41 additions & 2 deletions samples/client/echo_api/go/client.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading