[BUG][Go] anyOf with objects and arrays generates uncompilable model
Created by: MarcelGosselin
Bug Report Checklist
-
Have you provided a full/minimal spec to reproduce the issue? -
Have you validated the input using an OpenAPI validator (example)? -
Have you tested with the latest master to confirm the issue still exists? -
Have you searched for related issues/PRs? -
What's the actual output vs expected output? -
[Optional] Sponsorship to speed up the bug fix or feature request (example)
Description
When a schema has anyOf whose entries are either a plain object or an array, the generated code contains invalid field names in the model.
Actual output:
type Any struct {
[]Any *[]Any
map[string]interface{} *map[string]interface{}
}
Expected output (not necessarily an exact match):
type Any struct {
arrayOfAny *[]Any
plainObject *map[string]interface{}
}
openapi-generator version
6.0.1
OpenAPI declaration file content or url
OpenAPI with objects and arrays
Generation Details
Running the following without config file, from a folder containing only the file openapi.json
docker run --rm -it -v $(pwd):/src openapitools/openapi-generator-cli:v6.0.1 generate -i /src/openapi.json -g go -o /src
Steps to reproduce
- Generate using above command line
- Look at file
model_any.go, it contains invalid property names[]Anyandmap[string]interface{}type Any struct { []Any *[]Any bool *bool float32 *float32 int32 *int32 map[string]interface{} *map[string]interface{} string *string }
Related issues/PRs
Suggest a fix
The file modules/openapi-generator/src/main/resources/go/model_anyof.mustache uses #anyOf which is a Set<string> in CodegenModel.java. Unfortunately in that case the string is a datatype that cannot be used as a field name. I can see 3 ways to fix this (my favorite is the third one):
- (I don't know if it is possible in Mustache) In the mustache template, instead of
you could have something to normalize the identifier
{{#anyOf}} {{{.}}} *{{{.}}} {{/anyOf}}{{#anyOf}} {{{ toIdentifier(.) }}} *{{{.}}} {{/anyOf}} - Change the data type of the Set of CodegenModel.anyOf to be a class which contains 2 properties: DataType, IdentifierName. Then modify usages of anyOf in
model_anyof.mustacheand any other places to use the right property. - Use type definitions in Go anytime you encounter an array or object, something like the following.
You could then use that typedef in the
type openApiObject map[string]interface{} type arrayOfAny []AnySet<string>which would make the generation give this insteadtype Any struct { arrayOfAny *arrayOfAny bool *bool float32 *float32 int32 *int32 openApiObject *openApiObject string *string }