Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
package validate

import (
"bytes"
"encoding/json"
"io"
"net/http"
Expand Down Expand Up @@ -106,6 +107,10 @@ type GlobalOption struct {
//
// default: false
ValidatePrivateFields bool

// RestoreRequestBody Whether to restore the request body after reading it.
// default: false
RestoreRequestBody bool
}

// global options
Expand Down Expand Up @@ -396,6 +401,10 @@ func FromRequest(r *http.Request, maxMemoryLimit ...int64) (DataFace, error) {
if err != nil {
return nil, err
}
// restore request body
if gOpt.RestoreRequestBody {
r.Body = io.NopCloser(bytes.NewBuffer(bs))
}
return FromJSONBytes(bs)
}

Expand Down
35 changes: 35 additions & 0 deletions validate_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package validate

import (
"bytes"
"fmt"
"io"
"net/http"
"reflect"
"strings"
"testing"
Expand Down Expand Up @@ -274,3 +277,35 @@ func TestStruct_json_tag_name_parsing(t *testing.T) {
errStr = v.Errors["Field"]["email"]
assert.True(t, strings.HasPrefix(errStr, "Field "))
}

func TestValidation_RestoreRequestBody(t *testing.T) {
request, err := http.NewRequest(http.MethodPost, "/", bytes.NewBufferString(`{"test": "data"}`))
assert.Nil(t, err)
request.Header.Set("Content-Type", "application/json")

data, err := FromRequest(request)
assert.Nil(t, err)
assert.NotNil(t, data)

bs, err := io.ReadAll(request.Body)
assert.Nil(t, err)
assert.Empty(t, bs)

// restore body
Config(func(opt *GlobalOption) {
opt.RestoreRequestBody = true
})

request, err = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString(`{"test": "data"}`))
assert.Nil(t, err)
request.Header.Set("Content-Type", "application/json")

data, err = FromRequest(request)
assert.Nil(t, err)
assert.NotNil(t, data)

bs, err = io.ReadAll(request.Body)
assert.Nil(t, err)
assert.Equal(t, `{"test": "data"}`, string(bs))

}
Loading