Skip to content

Commit 6834b55

Browse files
committed
otelhttp: Remove custom wrapper after handling request
Signed-off-by: Janusz Marcinkiewicz <[email protected]>
1 parent 3ea6585 commit 6834b55

File tree

2 files changed

+8
-0
lines changed

2 files changed

+8
-0
lines changed

instrumentation/net/http/otelhttp/handler.go

+5
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,12 @@ func (h *middleware) serveHTTP(w http.ResponseWriter, r *http.Request, next http
140140
// ReadCloser fulfills a certain interface and it is indeed nil or NoBody.
141141
bw := request.NewBodyWrapper(r.Body, readRecordFunc)
142142
if r.Body != nil && r.Body != http.NoBody {
143+
prevBody := r.Body
143144
r.Body = bw
145+
146+
// Restore the original body after the request is processed to avoid issues
147+
// with extra wrapper since `http/server.go` later checks type of `r.Body`.
148+
defer func() { r.Body = prevBody }()
144149
}
145150

146151
writeRecordFunc := func(int64) {}

instrumentation/net/http/otelhttp/handler_test.go

+3
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import (
1717
"github.com/stretchr/testify/assert"
1818
"github.com/stretchr/testify/require"
1919

20+
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request"
2021
"go.opentelemetry.io/otel/attribute"
2122
"go.opentelemetry.io/otel/codes"
2223
"go.opentelemetry.io/otel/propagation"
@@ -99,6 +100,8 @@ func TestHandler(t *testing.T) {
99100
rr := httptest.NewRecorder()
100101
tc.handler(t).ServeHTTP(rr, r)
101102
assert.Equal(t, tc.expectedStatusCode, rr.Result().StatusCode) //nolint:bodyclose // False positive for httptest.ResponseRecorder: https://github.com/timakin/bodyclose/issues/59.
103+
_, ok := r.Body.(*request.BodyWrapper)
104+
assert.Falsef(t, ok, "body should not be wrapped after request is processed")
102105
})
103106
}
104107
}

0 commit comments

Comments
 (0)