Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handling Defaults #136

Open
injeniero opened this issue Feb 8, 2024 · 2 comments
Open

Handling Defaults #136

injeniero opened this issue Feb 8, 2024 · 2 comments

Comments

@injeniero
Copy link
Contributor

injeniero commented Feb 8, 2024

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 {
    ...
  }
}
@LucasRoesler
Copy link
Member

I like this idea

@injeniero
Copy link
Contributor Author

I'm working on PR for this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants