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
20.56k stars 6.28k forks source link

[BUG][Go] OpenAPI generator cannot generate required fields with omitempty #8841

Open miguelsorianod opened 3 years ago

miguelsorianod commented 3 years ago
Description

Hi,

With the openapi-generator Go code generator, it seems it is not possible to generate a Go struct attribute that is a pointer to a type and at the same time contains the omitempty json struct tag when the required OpenAPI attribute is set.

We have the following use case where it seems this would be needed:

We want to define a property that is required and that the user should set and should set it to a non-null value. From our code we need to be able to differentiate between the user not having set the value and having set it to its zero-value.

When digging deeper:

  1. We want to define an integer attribute as required at OpenAPI level. This integer attribute can have 0 as a valid value.
  2. In our code we need to be able to differentiate between the user having explicitly set the attribute to 0 and not having set the value at all. Thus, the only option we have is to have to Go autogenerated field as a pointer.
  3. We don't want to explicitly serialize that field when the pointer value is null, so the omitempty json struct tag is needed.
  4. The only way to have the omitempty json struct tag seems to be removing the 'required' property at OpenAPI level, but if we do so then at documentation level the attribute is shown as optional when it shouldn't be optional, we want the user to provide a non-null value always
openapi-generator version

openapi-generator-cli 4.3.1

Thank you

wing328 commented 3 years ago

openapi-generator-cli 4.3.1

Tried newer stable version 5.0.1 instead as the Go client generator has been refactored in the 5.x release.

miguelsorianod commented 3 years ago

Hi,

I've tried 5.0.1 but I think I still can't get the desired behavior.

The use case we want is: On OpenAPI side we want to specify that a user needs to send a mandatory attribute, and it cannot send it as null, and in Go code side we need to be able to detect whether the user has specified the attribute or not. This is, a mandatory, non-nullable value.

If in OpenAPI model (using 5.0.1) I set 'required' to true and 'nullable' to false then it is always generated as int32. That doesn't allow us to check whether the user has set the value to its zero value or has not set it at all.