Skip to content

Commit

Permalink
fix: Include request body in event payload (#94)
Browse files Browse the repository at this point in the history
Fixes #84
  • Loading branch information
flash286 authored and rhcarvalho committed Dec 10, 2019
1 parent d30c037 commit c558d82
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 7 deletions.
15 changes: 8 additions & 7 deletions interfaces.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package sentry

import (
"bytes"
"context"
"fmt"
"io/ioutil"
Expand Down Expand Up @@ -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
}

Expand Down
28 changes: 28 additions & 0 deletions interfaces_test.go
Original file line number Diff line number Diff line change
@@ -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)
})
}

0 comments on commit c558d82

Please sign in to comment.