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.29k stars 6.44k forks source link

[BUG][Go] enumUnknownDefaultCase does not return default case on JSON unmarshal #18747

Open jonrosner opened 3 months ago

jonrosner commented 3 months ago

Bug Report Checklist

Description

When using the additional parameter enumUnknownDefaultCase for other languages like Java, if the provided enum value is not found, the default case is returned. For Go that is not the case. Always the same error is provided, no matter the value of additional parameter.

openapi-generator version

7.6.0, no regression AFAIK

OpenAPI declaration file content or url
openapi: 3.0.1
info:
  version: 1.0.0
  title: Test API
paths: {}
components:
  schemas:
    TestEnum:
      type: string
      enum:
        - SOME_VALUE
        - SOME_OTHER_VALUE

Output code:

// List of TestEnum
const (
    TESTENUM_VALUE TestEnum = "SOME_VALUE"
    TESTENUM_OTHER_VALUE TestEnum = "SOME_OTHER_VALUE"
    TESTENUM_UNKNOWN_DEFAULT_OPEN_API TestEnum = "11184809"
)
...
func (v *TestEnum) UnmarshalJSON(src []byte) error {
    var value string
    err := json.Unmarshal(src, &value)
    if err != nil {
        return err
    }
    enumTypeValue := TestEnum(value)
    for _, existing := range AllowedTestEnumEnumValues {
        if existing == enumTypeValue {
            *v = enumTypeValue
            return nil
        }
    }

    return fmt.Errorf("%+v is not a valid TestEnum", value) <-- this line is the problem
}
...
Steps to reproduce

Simply run:

$ openapi-generator-cli generate \
                -i openapi.yaml \
                -g go \
                --additional-properties enumUnknownDefaultCase=true
Related issues/PRs

Link to the related PR: https://github.com/OpenAPITools/openapi-generator/pull/18748

Suggest a fix
func (v *{{{classname}}}) UnmarshalJSON(src []byte) error {
    var value {{{format}}}{{^format}}{{dataType}}{{/format}}
    err := json.Unmarshal(src, &value)
    if err != nil {
        return err
    }
    enumTypeValue := {{{classname}}}(value)
    for _, existing := range Allowed{{{classname}}}EnumValues {
        if existing == enumTypeValue {
            *v = enumTypeValue
            return nil
        }
    }

    {{#enumUnknownDefaultCase}}
    {{#allowableValues}}
    {{#enumVars}}
    {{#-last}}
    *v = {{{name}}}
    return nil
    {{/-last}}
    {{/enumVars}}
    {{/allowableValues}}
    {{/enumUnknownDefaultCase}}
    {{^enumUnknownDefaultCase}}
    return fmt.Errorf("%+v is not a valid {{classname}}", value)
    {{/enumUnknownDefaultCase}}
}
PatrickEsperoTech commented 3 months ago

Having the same issue right now