Skip to content

Commit

Permalink
Validate JSON body before unmarshalling into input type
Browse files Browse the repository at this point in the history
  • Loading branch information
Leskodamus committed Jul 3, 2024
1 parent 15a0c23 commit 54adc8b
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 19 deletions.
30 changes: 12 additions & 18 deletions request/jsonbody.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,34 +36,28 @@ func decodeJSONBody(readJSON func(rd io.Reader, v interface{}) error, tolerateFo
return nil
}

var (
rd io.Reader = r.Body
b *bytes.Buffer
)
var b *bytes.Buffer

Check failure on line 39 in request/jsonbody.go

View workflow job for this annotation

GitHub Actions / golangci-lint

S1021: should merge variable declaration with assignment on next line (gosimple)

validate := validator != nil && validator.HasConstraints(rest.ParamInBody)

if validate {
b = bufPool.Get().(*bytes.Buffer) //nolint:errcheck // bufPool is configured to provide *bytes.Buffer.
defer bufPool.Put(b)
b = bufPool.Get().(*bytes.Buffer) //nolint:errcheck // bufPool is configured to provide *bytes.Buffer.
defer bufPool.Put(b)
b.Reset()

b.Reset()
rd = io.TeeReader(r.Body, b)
// Read body into buffer.
if _, err := b.ReadFrom(r.Body); err != nil {
return err

Check notice on line 47 in request/jsonbody.go

View workflow job for this annotation

GitHub Actions / test (1.22.x)

1 statement(s) on lines 46:48 are not covered by tests.
}

err := readJSON(rd, &input)
if err != nil {
return fmt.Errorf("failed to decode json: %w", err)
}
validate := validator != nil && validator.HasConstraints(rest.ParamInBody)

if validator != nil && validate {
err = validator.ValidateJSONBody(b.Bytes())
if validate {
// Perform validation before unmarshalling into input object.
err := validator.ValidateJSONBody(b.Bytes())
if err != nil {
return err
}
}

return nil
return readJSON(b, input)
}
}

Expand Down
2 changes: 1 addition & 1 deletion request/jsonbody_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ func Test_decodeJSONBody_unmarshalFailed(t *testing.T) {
var i []int

err = decodeJSONBody(readJSON, false)(req, &i, nil)
assert.EqualError(t, err, "failed to decode json: json: cannot unmarshal number into Go value of type []int")
assert.EqualError(t, err, "json: cannot unmarshal number into Go value of type []int")
}

func Test_decodeJSONBody_validateFailed(t *testing.T) {
Expand Down

0 comments on commit 54adc8b

Please sign in to comment.