Skip to content

Commit cb44d5b

Browse files
vvbmohamuni
authored andcommitted
[Go] Set Default Values for Required Variables when a default is defined (OpenAPITools#19232)
* use default values for required vars when available * update tests to existing config file * cleanup OAS test * Remove setting value in Get. * Use Pascal Case for variable naming in Getter Function * add a CLI option * add a CLI option * add a CLI option
1 parent 26a164e commit cb44d5b

38 files changed

+413
-23
lines changed

bin/configs/go-petstore.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ additionalProperties:
1515
packageName: petstore
1616
disallowAdditionalPropertiesIfNotPresent: false
1717
generateInterfaces: true
18+
useDefaultValuesForRequiredVars: "true"
1819
enumNameMappings:
1920
delivered: SHIPPED
2021

docs/generators/go.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
2929
|packageVersion|Go package version.| |1.0.0|
3030
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
3131
|structPrefix|whether to prefix struct with the class name. e.g. DeletePetOpts => PetApiDeletePetOpts| |false|
32+
|useDefaultValuesForRequiredVars|Use default values for required variables when available| |false|
3233
|useOneOfDiscriminatorLookup|Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and only one match in oneOf's schemas) will be skipped.| |false|
3334
|withAWSV4Signature|whether to include AWS v4 signature support| |false|
3435
|withGoMod|Generate go.mod and go.sum| |true|

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -449,4 +449,6 @@ public static enum ENUM_PROPERTY_NAMING_TYPE {camelCase, PascalCase, snake_case,
449449
public static final String MAX_ATTEMPTS_FOR_RETRY = "maxAttemptsForRetry";
450450

451451
public static final String WAIT_TIME_OF_THREAD = "waitTimeMillis";
452+
453+
public static final String USE_DEFAULT_VALUES_FOR_REQUIRED_VARS = "useDefaultValuesForRequiredVars";
452454
}

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

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -40,15 +40,26 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
4040
private final Logger LOGGER = LoggerFactory.getLogger(AbstractGoCodegen.class);
4141
private static final String NUMERIC_ENUM_PREFIX = "_";
4242

43-
@Setter protected boolean withGoCodegenComment = false;
44-
@Setter protected boolean withAWSV4Signature = false;
45-
@Setter protected boolean withXml = false;
46-
@Setter protected boolean enumClassPrefix = false;
47-
@Setter protected boolean structPrefix = false;
48-
@Setter protected boolean generateInterfaces = false;
49-
@Setter protected boolean withGoMod = false;
50-
@Setter protected boolean generateMarshalJSON = true;
51-
@Setter protected boolean generateUnmarshalJSON = true;
43+
@Setter
44+
protected boolean withGoCodegenComment = false;
45+
@Setter
46+
protected boolean withAWSV4Signature = false;
47+
@Setter
48+
protected boolean withXml = false;
49+
@Setter
50+
protected boolean enumClassPrefix = false;
51+
@Setter
52+
protected boolean structPrefix = false;
53+
@Setter
54+
protected boolean generateInterfaces = false;
55+
@Setter
56+
protected boolean withGoMod = false;
57+
@Setter
58+
protected boolean generateMarshalJSON = true;
59+
@Setter
60+
protected boolean generateUnmarshalJSON = true;
61+
@Setter
62+
protected boolean useDefaultValuesForRequiredVars = false;
5263

5364
@Setter protected String packageName = "openapi";
5465
protected Set<String> numberTypes;

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ public class GoClientCodegen extends AbstractGoCodegen {
5555
public static final String GENERATE_INTERFACES = "generateInterfaces";
5656
public static final String MODEL_FILE_FOLDER = "modelFileFolder";
5757
public static final String WITH_GO_MOD = "withGoMod";
58+
public static final String USE_DEFAULT_VALUES_FOR_REQUIRED_VARS = "useDefaultValuesForRequiredVars";
5859
@Setter protected String goImportAlias = "openapiclient";
5960
protected boolean isGoSubmodule = false;
6061
@Setter protected boolean useOneOfDiscriminatorLookup = false; // use oneOf discriminator's mapping for model lookup
@@ -126,6 +127,7 @@ public GoClientCodegen() {
126127
cliOptions.add(CliOption.newBoolean(STRUCT_PREFIX, "whether to prefix struct with the class name. e.g. DeletePetOpts => PetApiDeletePetOpts"));
127128
cliOptions.add(CliOption.newBoolean(WITH_AWSV4_SIGNATURE, "whether to include AWS v4 signature support"));
128129
cliOptions.add(CliOption.newBoolean(GENERATE_INTERFACES, "Generate interfaces for api classes"));
130+
cliOptions.add(CliOption.newBoolean(USE_DEFAULT_VALUES_FOR_REQUIRED_VARS, "Use default values for required variables when available"));
129131

130132
// option to change the order of form/body parameter
131133
cliOptions.add(CliOption.newBoolean(
@@ -246,6 +248,11 @@ public void processOpts() {
246248
additionalProperties.put(GENERATE_INTERFACES, generateInterfaces);
247249
}
248250

251+
if (additionalProperties.containsKey(USE_DEFAULT_VALUES_FOR_REQUIRED_VARS)) {
252+
setUseDefaultValuesForRequiredVars(Boolean.parseBoolean(additionalProperties.get(USE_DEFAULT_VALUES_FOR_REQUIRED_VARS).toString()));
253+
additionalProperties.put(USE_DEFAULT_VALUES_FOR_REQUIRED_VARS, useDefaultValuesForRequiredVars);
254+
}
255+
249256
// Generate the 'signing.py' module, but only if the 'HTTP signature' security scheme is specified in the OAS.
250257
Map<String, SecurityScheme> securitySchemeMap = openAPI != null ?
251258
(openAPI.getComponents() != null ? openAPI.getComponents().getSecuritySchemes() : null) : null;

modules/openapi-generator/src/main/resources/go/model_simple.mustache

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,18 @@ func (o *{{classname}}) Set{{name}}(v {{vendorExtensions.x-go-base-type}}) {
168168
{{/isNullable}}
169169
}
170170

171+
{{#useDefaultValuesForRequiredVars}}
172+
{{^isReadOnly}}
173+
{{#defaultValue}}
174+
// GetDefault{{baseName}} function assigns the default value {{defaultValue}} to the {{name}} field
175+
// of the {{classname}} struct and returns the {{{defaultValue}}}.
176+
func (o *{{classname}}) GetDefault{{nameInPascalCase}}() interface{} {
177+
return {{{defaultValue}}}
178+
}
179+
{{/defaultValue}}
180+
{{/isReadOnly}}
181+
{{/useDefaultValuesForRequiredVars}}
182+
171183
{{/required}}
172184
{{^required}}
173185
// Get{{name}} returns the {{name}} field value if set, zero value otherwise{{#isNullable}} (both if not set or set to explicit null){{/isNullable}}.
@@ -318,6 +330,15 @@ func (o {{classname}}) ToMap() (map[string]interface{}, error) {
318330
{{! if argument is not nullable, don't set it if it is nil}}
319331
{{^isNullable}}
320332
{{#required}}
333+
{{#useDefaultValuesForRequiredVars}}
334+
{{^isReadOnly}}
335+
{{#defaultValue}}
336+
if _, exists := toSerialize["{{{baseName}}}"]; !exists {
337+
toSerialize["{{{baseName}}}"] = o.GetDefault{{nameInPascalCase}}()
338+
}
339+
{{/defaultValue}}
340+
{{/isReadOnly}}
341+
{{/useDefaultValuesForRequiredVars}}
321342
toSerialize["{{{baseName}}}"] = o.{{name}}
322343
{{/required}}
323344
{{^required}}
@@ -356,6 +377,20 @@ func (o *{{{classname}}}) UnmarshalJSON(data []byte) (err error) {
356377
{{/requiredVars}}
357378
}
358379
380+
{{#useDefaultValuesForRequiredVars}}
381+
// defaultValueFuncMap captures the default values for required properties.
382+
// These values are used when required properties are missing from the payload.
383+
defaultValueFuncMap := map[string]func() interface{} {
384+
{{#requiredVars}}
385+
{{#defaultValue}}
386+
{{^isReadOnly}}
387+
"{{baseName}}": o.GetDefault{{nameInPascalCase}},
388+
{{/isReadOnly}}
389+
{{/defaultValue}}
390+
{{/requiredVars}}
391+
}
392+
var defaultValueApplied bool
393+
{{/useDefaultValuesForRequiredVars}}
359394
allProperties := make(map[string]interface{})
360395
361396
err = json.Unmarshal(data, &allProperties)
@@ -365,11 +400,30 @@ func (o *{{{classname}}}) UnmarshalJSON(data []byte) (err error) {
365400
}
366401
367402
for _, requiredProperty := range(requiredProperties) {
403+
{{#useDefaultValuesForRequiredVars}}
404+
if value, exists := allProperties[requiredProperty]; !exists || value == "" {
405+
if _, ok := defaultValueFuncMap[requiredProperty]; ok {
406+
allProperties[requiredProperty] = defaultValueFuncMap[requiredProperty]()
407+
defaultValueApplied = true
408+
}
409+
}
410+
if value, exists := allProperties[requiredProperty]; !exists || value == ""{
411+
{{/useDefaultValuesForRequiredVars}}
412+
{{^useDefaultValuesForRequiredVars}}
368413
if _, exists := allProperties[requiredProperty]; !exists {
414+
{{/useDefaultValuesForRequiredVars}}
369415
return fmt.Errorf("no value given for required property %v", requiredProperty)
370416
}
371417
}
372418
419+
{{#useDefaultValuesForRequiredVars}}
420+
if defaultValueApplied {
421+
data, err = json.Marshal(allProperties)
422+
if err != nil{
423+
return err
424+
}
425+
}
426+
{{/useDefaultValuesForRequiredVars}}
373427
{{/hasRequired}}
374428
{{#isAdditionalPropertiesTrue}}
375429
{{#parent}}

modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoClientOptionsTest.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,5 +54,6 @@ protected void verifyOptions() {
5454
verify(clientCodegen).setWithGoMod(GoClientOptionsProvider.WITH_GO_MOD_VALUE);
5555
verify(clientCodegen).setGenerateMarshalJSON(GoClientOptionsProvider.GENERATE_MARSHAL_JSON_VALUE);
5656
verify(clientCodegen).setGenerateUnmarshalJSON(GoClientOptionsProvider.GENERATE_UNMARSHAL_JSON_VALUE);
57+
verify(clientCodegen).setUseDefaultValuesForRequiredVars(GoClientOptionsProvider.USE_DEFAULT_VALUES_FOR_REQUIRED_VARS_VALUE);
5758
}
5859
}

modules/openapi-generator/src/test/java/org/openapitools/codegen/options/GoClientOptionsProvider.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ public class GoClientOptionsProvider implements OptionsProvider {
3939
public static final boolean WITH_GO_MOD_VALUE = true;
4040
public static final boolean GENERATE_MARSHAL_JSON_VALUE = true;
4141
public static final boolean GENERATE_UNMARSHAL_JSON_VALUE = true;
42+
public static final boolean USE_DEFAULT_VALUES_FOR_REQUIRED_VARS_VALUE = true;
4243

4344
@Override
4445
public String getLanguage() {
@@ -64,6 +65,7 @@ public Map<String, String> createOptions() {
6465
.put(CodegenConstants.GENERATE_UNMARSHAL_JSON, "true")
6566
.put("generateInterfaces", "true")
6667
.put("structPrefix", "true")
68+
.put(CodegenConstants.USE_DEFAULT_VALUES_FOR_REQUIRED_VARS, "true")
6769
.build();
6870
}
6971

samples/client/echo_api/go-external-refs/model_pet.go

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

samples/client/echo_api/go/model_pet.go

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

samples/client/others/go/allof_multiple_ref_and_discriminator/model_additional_data.go

Lines changed: 4 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

samples/client/others/go/allof_multiple_ref_and_discriminator/model_base_item.go

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

samples/client/others/go/allof_multiple_ref_and_discriminator/model_final_item.go

Lines changed: 4 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

samples/client/others/go/oneof-anyof-required/model_nested_object1.go

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

samples/client/others/go/oneof-anyof-required/model_nested_object2.go

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

samples/client/petstore/go/go-petstore/model_animal.go

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

samples/client/petstore/go/go-petstore/model_category.go

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

samples/client/petstore/go/go-petstore/model_enum_test_.go

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

samples/client/petstore/go/go-petstore/model_format_test_.go

Lines changed: 4 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

samples/client/petstore/go/go-petstore/model_name.go

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)