Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

contrib/net/http: copy request in RoundTrip #1254

Merged
merged 13 commits into from
Jul 7, 2022
12 changes: 9 additions & 3 deletions contrib/net/http/roundtripper.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,19 @@ func (rt *roundTripper) RoundTrip(req *http.Request) (res *http.Response, err er
if rt.cfg.before != nil {
rt.cfg.before(req, span)
}
// inject the span context into the http request
err = tracer.Inject(span.Context(), tracer.HTTPHeadersCarrier(req.Header))
r2 := req.WithContext(ctx)
// deep copy of the Header
r2.Header = make(http.Header, len(req.Header))
for k, s := range req.Header {
r2.Header[k] = append([]string(nil), s...)
}
// inject the span context into the http request copy
err = tracer.Inject(span.Context(), tracer.HTTPHeadersCarrier(r2.Header))
if err != nil {
// this should never happen
fmt.Fprintf(os.Stderr, "contrib/net/http.Roundtrip: failed to inject http headers: %v\n", err)
}
res, err = rt.base.RoundTrip(req.WithContext(ctx))
res, err = rt.base.RoundTrip(r2)
if err != nil {
span.SetTag("http.errors", err.Error())
span.SetTag(ext.Error, err)
Expand Down
25 changes: 25 additions & 0 deletions contrib/net/http/roundtripper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,31 @@ func TestRoundTripperAnalyticsSettings(t *testing.T) {
})
}

// TestRoundTripperCopy is a regression test ensuring that RoundTrip
// does not modify the request per the RoundTripper contract. See:
// https://cs.opensource.google/go/go/+/refs/tags/go1.18.1:src/net/http/client.go;l=129-133
func TestRoundTripperCopy(t *testing.T) {
mt := mocktracer.Start()
defer mt.Stop()

s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, err := tracer.Extract(tracer.HTTPHeadersCarrier(r.Header))
assert.NoError(t, err)
w.Write([]byte("Hello World"))
}))
defer s.Close()

initialReq, err := http.NewRequest("GET", s.URL+"/hello/world", nil)
assert.NoError(t, err)
req, err := http.NewRequest("GET", s.URL+"/hello/world", nil)
assert.NoError(t, err)
rt := WrapRoundTripper(http.DefaultTransport).(*roundTripper)
_, err = rt.RoundTrip(req)
assert.NoError(t, err)
assert.Len(t, req.Header, 0)
assert.Equal(t, initialReq, req)
}

func TestServiceName(t *testing.T) {
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello World"))
Expand Down