diff --git a/interfaces.go b/interfaces.go index c7a042f59..15c0d007b 100644 --- a/interfaces.go +++ b/interfaces.go @@ -1,6 +1,7 @@ package sentry import ( + "bytes" "context" "fmt" "io/ioutil" @@ -101,15 +102,15 @@ func (r Request) FromHTTPRequest(request *http.Request) Request { r.QueryString = request.URL.RawQuery // Body - if request.GetBody != nil { - if bodyCopy, err := request.GetBody(); err == nil && bodyCopy != nil { - body, err := ioutil.ReadAll(bodyCopy) - if err == nil { - r.Data = string(body) - } + if request.Body != nil { + bodyBytes, err := ioutil.ReadAll(request.Body) + _ = request.Body.Close() + if err == nil { + // We have to restore original state of *request.Body + request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) + r.Data = string(bodyBytes) } } - return r } diff --git a/interfaces_test.go b/interfaces_test.go new file mode 100644 index 000000000..976bb3a62 --- /dev/null +++ b/interfaces_test.go @@ -0,0 +1,28 @@ +package sentry + +import ( + "bytes" + "io/ioutil" + "net/http" + "testing" +) + +func TestRequestFromHTTPRequest(t *testing.T) { + + var testPayload = `{"test_data": true}` + + t.Run("reading_body", func(t *testing.T) { + payload := bytes.NewBufferString(testPayload) + req, err := http.NewRequest("POST", "/test/", payload) + assertEqual(t, err, nil) + assertNotEqual(t, req, nil) + sentryRequest := Request{} + sentryRequest = sentryRequest.FromHTTPRequest(req) + assertEqual(t, sentryRequest.Data, testPayload) + + // Re-reading original *http.Request.Body + reqBody, err := ioutil.ReadAll(req.Body) + assertEqual(t, err, nil) + assertEqual(t, string(reqBody), testPayload) + }) +}