httpin icon indicating copy to clipboard operation
httpin copied to clipboard

Parse and validate custom time format

Open mxp7064 opened this issue 1 year ago • 5 comments

Hi, is there a way to parse and validate custom time format? For example, I want a query parameter which doesn't have to have a timezone, like: 2022-05-07T12:45:13

Thanks in advance!

mxp7064 avatar Jul 21 '22 17:07 mxp7064

Hi @mxp7064, here I'd like to talk about two cases:

1. All your code/apis are receiving time parameters without timezone, or more generally speaking, in one format.

We could replace the builtin time.Time type decoder with a custom one. See:

  • Default time.Time type decoder implementation: https://github.com/ggicci/httpin/blob/v0.9.0/internal/decoders.go#L173
  • httpin.ReplaceTypeDecoder
  • Example code: https://github.com/ggicci/httpin/blob/v0.9.0/decoder_test.go

2. In you project, different apis have different formats.

Currently, httpin's decoder interface doesn't support specifying extra parameters like "format". So it's not possible to achieve this.

However, there's a tricky way to handle this. Please take a look at the implementation of the builtin time.Time decoder, you may try different formats to parse the input value.

ggicci avatar Jul 22 '22 06:07 ggicci

BTW, the original implementation of the builtin time.Time type decoder also can be enhanced by trying several commonly used time formats. @ggicci

ggicci avatar Jul 22 '22 06:07 ggicci

@ggicci Think about using httpin.NewInput(...) to apply a custom type decoder by adding an optional parameter.

ggicci avatar Jul 23 '22 00:07 ggicci

Hi @mxp7064, I've introduce a special decoder directive in [email protected]. Take a look and I think this would help you.

Documentation: https://ggicci.github.io/httpin/directives/decoder

If it solved your problem, could you please close this issue?

ggicci avatar Jul 23 '22 10:07 ggicci

@ggicci Think about using httpin.NewInput(...) to apply a custom type decoder by adding an optional parameter.

It would be more helpful if we can allow overriding the decoder for each field in the struct.

ggicci avatar Jul 23 '22 10:07 ggicci