Skip to content

Handling Defaults #136

@injeniero

Description

@injeniero

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 {
    ...
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions