openapi-generator
openapi-generator copied to clipboard
[BUG][Go] enumUnknownDefaultCase does not return default case on JSON unmarshal
Bug Report Checklist
- [x] Have you provided a full/minimal spec to reproduce the issue?
- [x] Have you validated the input using an OpenAPI validator (example)?
- [x] Have you tested with the latest master to confirm the issue still exists?
- [x] Have you searched for related issues/PRs?
- [x] What's the actual output vs expected output?
- [ ] [Optional] Sponsorship to speed up the bug fix or feature request (example)
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}}
}