OpenAPITools / openapi-generator

OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)
https://openapi-generator.tech
Apache License 2.0
21.44k stars 6.48k forks source link

[BUG][Go] useOneOfDiscriminatorLookup generates invalid variable names for `oneOf` with no discriminator #18922

Closed sazapp-spectra closed 2 months ago

sazapp-spectra commented 3 months ago

Bug Report Checklist

Description

I'm trying to define a property in a schema that can be one of two types - a single date-time string or an array of strings. I'm using oneOf without a discriminator to do this. Also, in this same (rather large) schema, we have a few other instances of oneOf that do use discriminators, so we're setting useOneOfDiscriminatorLookup to true. The generated code looks something like this:

func (dst *BarProp) UnmarshalJSON(data []byte) error {
    var err error
    match := 0
    // try to unmarshal data into ArrayOfString
    err = json.Unmarshal(data, &dst.ArrayOfString)
    if err == nil {
        json[]string, _ := json.Marshal(dst.ArrayOfString)
        if string(json[]string) == "{}" { // empty struct
            dst.ArrayOfString = nil
        } else {
            match++
        }
    } else {
        dst.ArrayOfString = nil
    }

Note that json[]string isn't a valid variable name.

When I try it with useOneOfDiscriminatorLookup set to false, json[]string is named jsonArrayOfString, which compiles fine - this is what I'd expect the fix to do. In general, I'd expect the value of useOneOfDiscriminatorLookup to be irrelevant to code generated from a oneOf with no discriminator (more or less like what the linked issue seems to suggest).

openapi-generator version

7.5.0-SNAPSHOT

OpenAPI declaration file content or url

oneOf-array-of-strings.yaml

Generation Details
generate -g go -p useOneOfDiscriminatorLookup=true
Steps to reproduce
Related issues/PRs

[BUG][Go] UnmarshalJson has unused variable err if spec has oneOf without discriminator

Suggest a fix

I'm currently testing out just calling lambda.type-to-name in modules/openapi-generator/src/main/resources/go/model_oneof.mustache; specifically replacing the json{{.}} on line 61 with json{{#lambda.type-to-name}}{{{.}}}{{/lambda.type-to-name}}.

sazapp-spectra commented 2 months ago

fixed in https://github.com/OpenAPITools/openapi-generator/pull/19183