feat(transport/http): request body read multiple times (#2542)

* fix(transport/http): request body read multiple times

* feat(transport/http): request body read multiple times
pull/2243/merge
桂后昌 2 years ago committed by GitHub
parent e22775cfcc
commit b2689af39c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 6
      transport/http/codec.go
  2. 12
      transport/http/codec_test.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())
}

@ -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 {

Loading…
Cancel
Save