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
This commit is contained in:
Ihar Hrachyshka 2025-09-27 02:16:53 -04:00 committed by GitHub
parent dc0d5c6839
commit d8d9744154
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 16 additions and 4 deletions

View File

@ -115,6 +115,15 @@ public class CodegenOperation {
return nonEmpty(bodyParams);
}
/**
* Check if there's at least one optional body parameter
*
* @return true if optional body parameter exists, false otherwise
*/
public boolean getHasOptionalBodyParam() {
return nonEmpty(bodyParams) && nonEmpty(optionalParams) && bodyParams.stream().anyMatch(optionalParams::contains);
}
/**
* Check if there's at least one query parameter
*

View File

@ -410,6 +410,7 @@ public class GoServerCodegen extends AbstractGoCodegen {
private void addConditionalImportInformation(OperationsMap operations) {
boolean hasPathParams = false;
boolean hasBodyParams = false;
boolean hasOptionalBodyParams = false;
for (CodegenOperation op : operations.getOperations().getOperation()) {
if (op.getHasPathParams()) {
@ -418,10 +419,14 @@ public class GoServerCodegen extends AbstractGoCodegen {
if (op.getHasBodyParam()) {
hasBodyParams = true;
}
if (op.getHasOptionalBodyParam()) {
hasOptionalBodyParams = true;
}
}
additionalProperties.put("hasPathParams", hasPathParams);
additionalProperties.put("hasBodyParams", hasBodyParams);
additionalProperties.put("hasOptionalBodyParams", hasOptionalBodyParams);
}

View File

@ -6,12 +6,10 @@ import (
{{#hasBodyParams}}
"encoding/json"
{{/hasBodyParams}}
{{#isBodyParam}}
{{^required}}
{{#hasOptionalBodyParams}}
"errors"
"io"
{{/required}}
{{/isBodyParam}}
{{/hasOptionalBodyParams}}
"net/http"
"strings"
{{#imports}} "{{import}}"