diff --git a/transport/http/codec.go b/transport/http/codec.go index da1b13e062a..156181f77ff 100644 --- a/transport/http/codec.go +++ b/transport/http/codec.go @@ -1,8 +1,10 @@ package http import ( + "bytes" "fmt" "io" + "io/ioutil" "net/http" "net/url" @@ -63,6 +65,10 @@ func DefaultRequestDecoder(r *http.Request, v interface{}) error { return errors.BadRequest("CODEC", fmt.Sprintf("unregister Content-Type: %s", r.Header.Get("Content-Type"))) } data, err := io.ReadAll(r.Body) + + // reset body. + r.Body = ioutil.NopCloser(bytes.NewBuffer(data)) + if err != nil { return errors.BadRequest("CODEC", err.Error()) } diff --git a/transport/http/codec_test.go b/transport/http/codec_test.go index 562f55decf5..b701b70fc0a 100644 --- a/transport/http/codec_test.go +++ b/transport/http/codec_test.go @@ -11,9 +11,11 @@ import ( ) func TestDefaultRequestDecoder(t *testing.T) { + bodyString := "{\"a\":\"1\", \"b\": 2}" + req1 := &nethttp.Request{ Header: make(nethttp.Header), - Body: io.NopCloser(bytes.NewBufferString("{\"a\":\"1\", \"b\": 2}")), + Body: io.NopCloser(bytes.NewBufferString(bodyString)), } req1.Header.Set("Content-Type", "application/json") @@ -31,6 +33,14 @@ func TestDefaultRequestDecoder(t *testing.T) { if !reflect.DeepEqual(int64(2), v1.B) { t.Errorf("expected %v, got %v", 2, v1.B) } + + data, err := io.ReadAll(req1.Body) + if err != nil { + t.Errorf("expected no error, got %v", err1) + } + if !reflect.DeepEqual([]byte(bodyString), data) { + t.Errorf("expected %v, got %v", bodyString, data) + } } type mockResponseWriter struct {