Skip to content

Commit a00549c

Browse files
wing328rikotsev
andauthored
Add an option to skip unmarshall json in Go client generator (OpenAPITools#18448)
* feat(go): Add a vendor extension to option out of generating the UnmarshalJSON method * add generate unmarshal json option in go client generator * update doc --------- Co-authored-by: Radoslav Kotsev <[email protected]>
1 parent 3bd6d67 commit a00549c

File tree

10 files changed

+176
-1
lines changed

10 files changed

+176
-1
lines changed

docs/generators/go.md

+1
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
2222
|enumClassPrefix|Prefix enum with class name| |false|
2323
|generateInterfaces|Generate interfaces for api classes| |false|
2424
|generateMarshalJSON|Generate MarshalJSON method| |true|
25+
|generateUnmarshalJSON|Generate UnmarshalJSON method| |true|
2526
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
2627
|isGoSubmodule|whether the generated Go module is a submodule| |false|
2728
|packageName|Go package name (convention: lowercase).| |openapi|

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

+2
Original file line numberDiff line numberDiff line change
@@ -442,6 +442,8 @@ public static enum ENUM_PROPERTY_NAMING_TYPE {camelCase, PascalCase, snake_case,
442442
public static final String GENERATE_MARSHAL_JSON = "generateMarshalJSON";
443443
public static final String GENERATE_MARSHAL_JSON_DESC = "Generate MarshalJSON method";
444444

445+
public static final String GENERATE_UNMARSHAL_JSON = "generateUnmarshalJSON";
446+
public static final String GENERATE_UNMARSHAL_JSON_DESC = "Generate UnmarshalJSON method";
445447
public static final String MAX_ATTEMPTS_FOR_RETRY = "maxAttemptsForRetry";
446448

447449
public static final String WAIT_TIME_OF_THREAD = "waitTimeMillis";

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

+11-1
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
4848
protected boolean generateInterfaces = false;
4949
protected boolean withGoMod = false;
5050
protected boolean generateMarshalJSON = true;
51+
protected boolean generateUnmarshalJSON = true;
52+
5153

5254
protected String packageName = "openapi";
5355
protected Set<String> numberTypes;
@@ -775,7 +777,11 @@ public ModelsMap postProcessModels(ModelsMap objs) {
775777
}
776778

777779
if (generateMarshalJSON) {
778-
model.vendorExtensions.put("x-go-generate-marshal-json", true);
780+
model.vendorExtensions.putIfAbsent("x-go-generate-marshal-json", true);
781+
}
782+
783+
if (generateUnmarshalJSON) {
784+
model.vendorExtensions.putIfAbsent("x-go-generate-unmarshal-json", true);
779785
}
780786
}
781787

@@ -932,6 +938,10 @@ public void setGenerateMarshalJSON(boolean generateMarshalJSON) {
932938
this.generateMarshalJSON = generateMarshalJSON;
933939
}
934940

941+
public void setGenerateUnmarshalJSON(boolean generateUnmarshalJSON) {
942+
this.generateUnmarshalJSON = generateUnmarshalJSON;
943+
}
944+
935945
@Override
936946
public String toDefaultValue(Schema schema) {
937947
schema = unaliasSchema(schema);

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

+6
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,7 @@ public GoClientCodegen() {
150150
this.setDisallowAdditionalPropertiesIfNotPresent(true);
151151
cliOptions.add(CliOption.newBoolean(WITH_GO_MOD, "Generate go.mod and go.sum", true));
152152
cliOptions.add(CliOption.newBoolean(CodegenConstants.GENERATE_MARSHAL_JSON, CodegenConstants.GENERATE_MARSHAL_JSON_DESC, true));
153+
cliOptions.add(CliOption.newBoolean(CodegenConstants.GENERATE_UNMARSHAL_JSON, CodegenConstants.GENERATE_UNMARSHAL_JSON_DESC, true));
153154
this.setWithGoMod(true);
154155
}
155156

@@ -287,6 +288,11 @@ public void processOpts() {
287288
setGenerateMarshalJSON(Boolean.parseBoolean(additionalProperties.get(CodegenConstants.GENERATE_MARSHAL_JSON).toString()));
288289
}
289290

291+
if (additionalProperties.containsKey(CodegenConstants.GENERATE_UNMARSHAL_JSON)) {
292+
setGenerateUnmarshalJSON(Boolean.parseBoolean(additionalProperties.get(CodegenConstants.GENERATE_UNMARSHAL_JSON).toString()));
293+
}
294+
295+
290296
// add lambda for mustache templates to handle oneOf/anyOf naming
291297
// e.g. []string => ArrayOfString
292298
additionalProperties.put("lambda.type-to-name", (Mustache.Lambda) (fragment, writer) -> writer.write(typeToName(fragment.execute())));

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

+2
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,7 @@ func (o {{classname}}) ToMap() (map[string]interface{}, error) {
337337
return toSerialize, nil
338338
}
339339
340+
{{#vendorExtensions.x-go-generate-unmarshal-json}}
340341
{{#isAdditionalPropertiesTrue}}
341342
func (o *{{{classname}}}) UnmarshalJSON(data []byte) (err error) {
342343
{{/isAdditionalPropertiesTrue}}
@@ -514,4 +515,5 @@ func (o *{{{classname}}}) UnmarshalJSON(data []byte) (err error) {
514515
}
515516
516517
{{/isArray}}
518+
{{/vendorExtensions.x-go-generate-unmarshal-json}}
517519
{{>nullable_model}}

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

+42
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,48 @@ public void verifyApiWithAllOfMultipleRefAndDiscriminator() throws IOException {
312312
"BaseItem");
313313
}
314314

315+
@Test
316+
public void testVendorExtensionGenerateUnmarshalJson() throws IOException {
317+
File output = Files.createTempDirectory("test").toFile();
318+
output.deleteOnExit();
319+
320+
final CodegenConfigurator configurator = new CodegenConfigurator()
321+
.setGeneratorName("go")
322+
.setGitUserId("OpenAPITools")
323+
.setGitRepoId("openapi-generator")
324+
.setInputSpec("src/test/resources/3_0/go/allof_with_unmarshal_json.yaml")
325+
.setOutputDir(output.getAbsolutePath().replace("\\", "/"));
326+
327+
DefaultGenerator generator = new DefaultGenerator();
328+
List<File> files = generator.opts(configurator.toClientOptInput()).generate();
329+
files.forEach(File::deleteOnExit);
330+
331+
TestUtils.assertFileExists(Paths.get(output + "/model_base_item.go"));
332+
TestUtils.assertFileContains(Paths.get(output + "/model_base_item.go"),
333+
"func (o *BaseItem) UnmarshalJSON(data []byte) (err error) {");
334+
}
335+
336+
@Test
337+
public void testVendorExtensionSkipGenerateUnmarshalJson() throws IOException {
338+
File output = Files.createTempDirectory("test").toFile();
339+
output.deleteOnExit();
340+
341+
final CodegenConfigurator configurator = new CodegenConfigurator()
342+
.setGeneratorName("go")
343+
.setGitUserId("OpenAPITools")
344+
.setGitRepoId("openapi-generator")
345+
.setInputSpec("src/test/resources/3_0/go/allof_skip_unmarshal_json.yaml")
346+
.setOutputDir(output.getAbsolutePath().replace("\\", "/"));
347+
348+
DefaultGenerator generator = new DefaultGenerator();
349+
List<File> files = generator.opts(configurator.toClientOptInput()).generate();
350+
files.forEach(File::deleteOnExit);
351+
352+
TestUtils.assertFileExists(Paths.get(output + "/model_base_item.go"));
353+
TestUtils.assertFileNotContains(Paths.get(output + "/model_base_item.go"),
354+
"func (o *BaseItem) UnmarshalJSON(data []byte) (err error) {");
355+
}
356+
315357
@Test
316358
public void testAdditionalPropertiesWithGoMod() throws Exception {
317359
File output = Files.createTempDirectory("test").toFile();

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

+1
Original file line numberDiff line numberDiff line change
@@ -53,5 +53,6 @@ protected void verifyOptions() {
5353
verify(clientCodegen).setUseOneOfDiscriminatorLookup(GoClientOptionsProvider.USE_ONE_OF_DISCRIMINATOR_LOOKUP_VALUE);
5454
verify(clientCodegen).setWithGoMod(GoClientOptionsProvider.WITH_GO_MOD_VALUE);
5555
verify(clientCodegen).setGenerateMarshalJSON(GoClientOptionsProvider.GENERATE_MARSHAL_JSON_VALUE);
56+
verify(clientCodegen).setGenerateUnmarshalJSON(GoClientOptionsProvider.GENERATE_UNMARSHAL_JSON_VALUE);
5657
}
5758
}

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

+2
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ public class GoClientOptionsProvider implements OptionsProvider {
3838
public static final boolean USE_ONE_OF_DISCRIMINATOR_LOOKUP_VALUE = true;
3939
public static final boolean WITH_GO_MOD_VALUE = true;
4040
public static final boolean GENERATE_MARSHAL_JSON_VALUE = true;
41+
public static final boolean GENERATE_UNMARSHAL_JSON_VALUE = true;
4142

4243
@Override
4344
public String getLanguage() {
@@ -60,6 +61,7 @@ public Map<String, String> createOptions() {
6061
.put(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, "true")
6162
.put(CodegenConstants.WITH_GO_MOD, "true")
6263
.put(CodegenConstants.GENERATE_MARSHAL_JSON, "true")
64+
.put(CodegenConstants.GENERATE_UNMARSHAL_JSON, "true")
6365
.put("generateInterfaces", "true")
6466
.put("structPrefix", "true")
6567
.build();
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
openapi: 3.0.0
2+
info:
3+
title: Test
4+
version: 1.0.0
5+
paths: {}
6+
components:
7+
schemas:
8+
FinalItem:
9+
type: object
10+
allOf:
11+
- $ref: '#/components/schemas/BaseItem'
12+
- $ref: '#/components/schemas/AdditionalData'
13+
BaseItem:
14+
type: object
15+
x-go-generate-unmarshal-json: false
16+
properties:
17+
title:
18+
type: string
19+
type:
20+
type: string
21+
enum:
22+
- FINAL
23+
example: FINAL
24+
discriminator:
25+
propertyName: type
26+
mapping:
27+
FINAL: '#/components/schemas/FinalItem'
28+
required:
29+
- title
30+
- type
31+
AdditionalData:
32+
type: object
33+
properties:
34+
prop1:
35+
type: string
36+
quantity:
37+
type: integer
38+
format: int32
39+
example: 1
40+
minimum: 1
41+
unitPrice:
42+
type: number
43+
format: double
44+
example: 9.99
45+
minimum: 0.0
46+
totalPrice:
47+
type: number
48+
format: double
49+
example: 9.99
50+
minimum: 0.0
51+
required:
52+
- prop1
53+
- quantity
54+
- unitPrice
55+
- totalPrice
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
openapi: 3.0.0
2+
info:
3+
title: Test
4+
version: 1.0.0
5+
paths: {}
6+
components:
7+
schemas:
8+
FinalItem:
9+
type: object
10+
allOf:
11+
- $ref: '#/components/schemas/BaseItem'
12+
- $ref: '#/components/schemas/AdditionalData'
13+
BaseItem:
14+
type: object
15+
properties:
16+
title:
17+
type: string
18+
type:
19+
type: string
20+
enum:
21+
- FINAL
22+
example: FINAL
23+
discriminator:
24+
propertyName: type
25+
mapping:
26+
FINAL: '#/components/schemas/FinalItem'
27+
required:
28+
- title
29+
- type
30+
AdditionalData:
31+
type: object
32+
properties:
33+
prop1:
34+
type: string
35+
quantity:
36+
type: integer
37+
format: int32
38+
example: 1
39+
minimum: 1
40+
unitPrice:
41+
type: number
42+
format: double
43+
example: 9.99
44+
minimum: 0.0
45+
totalPrice:
46+
type: number
47+
format: double
48+
example: 9.99
49+
minimum: 0.0
50+
required:
51+
- prop1
52+
- quantity
53+
- unitPrice
54+
- totalPrice

0 commit comments

Comments
 (0)