You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When validating an input with an incorrect type we get an failed to decode json: json: cannot unmarshall... error instead of a validation failed error with a context object pointing to the issue. This is because the un-marshalling fails before the validator is even run.
First, instead of using a io.TeeReader, just read the request body into the buffer, then perform data validation and only then, if no error occurs, unmarshal the JSON bytes into the input object.
Something like this:
decodeJSONBody(readJSONfunc(rd io.Reader, vinterface{}) error, tolerateFormDatabool) valueDecoderFunc {
// ...varb*bytes.Bufferb=bufPool.Get().(*bytes.Buffer) //nolint:errcheck // bufPool is configured to provide *bytes.Buffer.deferbufPool.Put(b)
b.Reset()
// First read body into buffer.if_, err:=b.ReadFrom(r.Body); err!=nil {
returnerr
}
validate:=validator!=nil&&validator.HasConstraints(rest.ParamInBody)
ifvalidate {
// Perform validation before unmarshalling into input object.err:=validator.ValidateJSONBody(b.Bytes())
iferr!=nil {
returnerr
}
}
returnreadJSON(b, input)
}
Describe the bug
When validating an input with an incorrect type we get an
failed to decode json: json: cannot unmarshall...
error instead of avalidation failed
error with acontext
object pointing to the issue. This is because the un-marshalling fails before the validator is even run.To Reproduce
Expected behavior
I would expect a type mismatch issue to be reported in the same way as any other validation error to the end user
The text was updated successfully, but these errors were encountered: