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

Handling Defaults

Open injeniero opened this issue 1 year ago • 2 comments

The current implementation ignores default values. I would like to suggest the following changes:

  • Add const for value types for their default value, example for a named integer:
var DefaultPageSize = int32(20)
  • Add a factory function for Structs to set default values, example for a struct holding a named integer:
func NewPagination() *Pagination {
  return &Pagination{
    PageSize: DefaultPageSize
  }
}
  • Add UnmarshalJSON and UnmarshalYAML methods to set default values before deserialization happens. This is required to properly handle deserialization of slices and maps. The limitations is other Unmarshallers would not properly handle default values, but with JSON and YAML it should cover most of the use cases.

User code would need to use the factory function:

func MyRestEndpoint(input InPutRequest) {
  pagination := api.NewPagination()
  if err = json.Unmarshal(input.Content, pagination); err != nil {
    ...
  }
  
  if pagination.PageSize == api.DefaultPageSize {
    ...
  }
}

injeniero avatar Feb 08 '24 19:02 injeniero

I like this idea

LucasRoesler avatar Feb 09 '24 09:02 LucasRoesler

I'm working on PR for this.

injeniero avatar Feb 09 '24 21:02 injeniero