openapi-generator icon indicating copy to clipboard operation
openapi-generator copied to clipboard

[go-server] Set default values in object properties

Open rledisez opened this issue 1 year ago • 4 comments

When a default value is set for an object property, ensure it is set into the struct before decoding the JSON body.

Fix OpenAPITools#4579

rledisez avatar Apr 29 '24 11:04 rledisez

By applying the default values, this make the usage of default values of a post body consistent with the default values of query parameters

Any feedbacks appreciated @antihax @grokify @kemokemo @jirikuncar @ph4r5h4d @lwj5

rledisez avatar Apr 29 '24 12:04 rledisez

Does the default work when there are nested objects?

such as embedded struct, and when a struct is a type for one of the fields.

lwj5 avatar May 06 '24 12:05 lwj5

Does the default work when there are nested objects?

such as embedded struct, and when a struct is a type for one of the fields.

The previous version was not working in that case. It was just handling basic types (string, int, bool). I took inspiration of the function NewObjectWithDefaults from the "go" templates to create a function that create a struct with defaults for each type and call it when required. I think it does what you asked for.

rledisez avatar May 13 '24 12:05 rledisez

could you add some tests that generates as such:

struct A { S1 string }

struct B { A S2 string }

struct C { SomeA A S3 string }

This is B embeds A, and C has a field of type A. Make sure the code is generated correctly if S1 has a default.

lwj5 avatar May 19 '24 10:05 lwj5

Thx for your feedback. I updated the template to set default values for embedded structs. I created a test as samples/openapi3/server/petstore/go/model_store_test.go but I'm not sure this will be executed as the other tests in the same directory were broken (i fixed them).

rledisez avatar May 28 '24 10:05 rledisez