Skip to content

Commit d8d9744

Browse files
authored
go: Fix missing imports for optional body params. (#22014)
Previous mustache template was using #isBodyParam outside of #operation context, so it was not effective. Even if we'd add the proper context, we'd then risk generating duplicate imports for multiple matching parameters. For this reason, this patch implements detection of an optional body parameter in code, making sure the corresponding import is added just once. Fixes #19237
1 parent dc0d5c6 commit d8d9744

File tree

3 files changed

+16
-4
lines changed

3 files changed

+16
-4
lines changed

modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,15 @@ public boolean getHasBodyParam() {
115115
return nonEmpty(bodyParams);
116116
}
117117

118+
/**
119+
* Check if there's at least one optional body parameter
120+
*
121+
* @return true if optional body parameter exists, false otherwise
122+
*/
123+
public boolean getHasOptionalBodyParam() {
124+
return nonEmpty(bodyParams) && nonEmpty(optionalParams) && bodyParams.stream().anyMatch(optionalParams::contains);
125+
}
126+
118127
/**
119128
* Check if there's at least one query parameter
120129
*

modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoServerCodegen.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -410,6 +410,7 @@ public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List<Mo
410410
private void addConditionalImportInformation(OperationsMap operations) {
411411
boolean hasPathParams = false;
412412
boolean hasBodyParams = false;
413+
boolean hasOptionalBodyParams = false;
413414

414415
for (CodegenOperation op : operations.getOperations().getOperation()) {
415416
if (op.getHasPathParams()) {
@@ -418,10 +419,14 @@ private void addConditionalImportInformation(OperationsMap operations) {
418419
if (op.getHasBodyParam()) {
419420
hasBodyParams = true;
420421
}
422+
if (op.getHasOptionalBodyParam()) {
423+
hasOptionalBodyParams = true;
424+
}
421425
}
422426

423427
additionalProperties.put("hasPathParams", hasPathParams);
424428
additionalProperties.put("hasBodyParams", hasBodyParams);
429+
additionalProperties.put("hasOptionalBodyParams", hasOptionalBodyParams);
425430
}
426431

427432

modules/openapi-generator/src/main/resources/go-server/controller-api.mustache

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,10 @@ import (
66
{{#hasBodyParams}}
77
"encoding/json"
88
{{/hasBodyParams}}
9-
{{#isBodyParam}}
10-
{{^required}}
9+
{{#hasOptionalBodyParams}}
1110
"errors"
1211
"io"
13-
{{/required}}
14-
{{/isBodyParam}}
12+
{{/hasOptionalBodyParams}}
1513
"net/http"
1614
"strings"
1715
{{#imports}} "{{import}}"

0 commit comments

Comments
 (0)