thedevsaddam/govalidator

Cannot read body after JSON validation

System-Glitch opened this issue · 1 comments

The body cannot be retrieved after a JSON Validation. The only way to get it is to use v.Opts.Data.

The following line in the JSON validation code drains the request's body reader, rendering it unusable:

err := json.NewDecoder(v.Opts.Request.Body).Decode(v.Opts.Data)

Proposed solution: reset the read state after validation.

Current workaround:

var errors url.Values
var bodyBytes []byte
if r.Body != nil {
	bodyBytes, _ = ioutil.ReadAll(r.Body)
	validator.Opts.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
	errors = validator.ValidateJSON()
	validator.Opts.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
}

Closing as it's not really an issue. The parsed data is already available in v.Opts.Data and shouldn't be parsed multiple times.