Skip to content

Commit

Permalink
Fix trace request builder func (TykTechnologies#3262)
Browse files Browse the repository at this point in the history
When `tr.Path` was empty, it was giving error. So I change `httptest.NewRequest()` to `http.NewRequest()`.

Fixes TykTechnologies/tyk-analytics#2031
  • Loading branch information
furkansenharputlu committed Aug 10, 2020
1 parent 931118f commit 49161a3
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 6 deletions.
17 changes: 11 additions & 6 deletions gateway/tracing.go
Expand Up @@ -21,10 +21,11 @@ type traceHttpRequest struct {
Headers http.Header `json:"headers"`
}

func (tr *traceHttpRequest) toRequest() *http.Request {
r := httptest.NewRequest(tr.Method, tr.Path, strings.NewReader(tr.Body))
// It sets example.com by default. Setting it to empty will not show a value because it is not necessary.
r.Host = ""
func (tr *traceHttpRequest) toRequest() (*http.Request, error) {
r, err := http.NewRequest(tr.Method, tr.Path, strings.NewReader(tr.Body))
if err != nil {
return nil, err
}

for key, values := range tr.Headers {
for _, v := range values {
Expand All @@ -34,7 +35,7 @@ func (tr *traceHttpRequest) toRequest() *http.Request {

ctxSetTrace(r)

return r
return r, nil
}

// TraceRequest is for tracing an HTTP request
Expand Down Expand Up @@ -125,7 +126,11 @@ func traceHandler(w http.ResponseWriter, r *http.Request) {
}

wr := httptest.NewRecorder()
tr := traceReq.Request.toRequest()
tr, err := traceReq.Request.toRequest()
if err != nil {
doJSONWrite(w, http.StatusInternalServerError, apiError("Unexpected failure: "+err.Error()))
return
}
nopCloseRequestBody(tr)
chainObj.ThisHandler.ServeHTTP(wr, tr)

Expand Down
26 changes: 26 additions & 0 deletions gateway/tracing_test.go
@@ -0,0 +1,26 @@
package gateway

import (
"io/ioutil"
"net/http"
"testing"

"github.com/stretchr/testify/assert"
)

func TestTraceHttpRequest_toRequest(t *testing.T) {
const body = `{"foo":"bar"}`
header := http.Header{}
header.Add("key", "value")
tr := &traceHttpRequest{Path: "", Method: http.MethodPost, Body: body, Headers: header}

request, err := tr.toRequest()
bodyInBytes, _ := ioutil.ReadAll(request.Body)

assert.NoError(t, err)
assert.Equal(t, http.MethodPost, request.Method)
assert.Equal(t, "", request.URL.Host)
assert.Equal(t, "", request.URL.Path)
assert.Equal(t, header, request.Header)
assert.Equal(t, string(bodyInBytes), body)
}

0 comments on commit 49161a3

Please sign in to comment.