Skip to content

Commit 85d875f

Browse files
dmathieuMrAlias
authored andcommitted
Don't write headers on Write if they were already written (open-telemetry#6055)
The change in open-telemetry#5916 introduced a regression, as we don't check whether the header was written before writing it in `Write()`. We need to only write if the header wasn't written yet. Fixes open-telemetry#6053. --------- Co-authored-by: Tyler Yahn <[email protected]>
1 parent fc25f67 commit 85d875f

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
88

99
## [Unreleased]
1010

11+
### Fixed
12+
13+
- Superfluous call to `WriteHeader` when writing the response body after setting a status code in `go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp`. (#6055)
14+
1115
<!-- Released section -->
1216
<!-- Don't change this section unless doing release -->
1317

instrumentation/net/http/otelhttp/internal/request/resp_writer_wrapper.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,9 @@ func (w *RespWriterWrapper) Write(p []byte) (int, error) {
4444
w.mu.Lock()
4545
defer w.mu.Unlock()
4646

47-
w.writeHeader(http.StatusOK)
47+
if !w.wroteHeader {
48+
w.writeHeader(http.StatusOK)
49+
}
4850

4951
n, err := w.ResponseWriter.Write(p)
5052
n1 := int64(n)

instrumentation/net/http/otelhttp/test/handler_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,21 @@ func TestHandlerPropagateWriteHeaderCalls(t *testing.T) {
250250
},
251251
expectHeadersWritten: []int{http.StatusInternalServerError, http.StatusOK},
252252
},
253+
{
254+
name: "When writing the header indirectly through body write",
255+
handler: func(w http.ResponseWriter, r *http.Request) {
256+
_, _ = w.Write([]byte("hello"))
257+
},
258+
expectHeadersWritten: []int{http.StatusOK},
259+
},
260+
{
261+
name: "With a header already written when writing the body",
262+
handler: func(w http.ResponseWriter, r *http.Request) {
263+
w.WriteHeader(http.StatusBadRequest)
264+
_, _ = w.Write([]byte("hello"))
265+
},
266+
expectHeadersWritten: []int{http.StatusBadRequest},
267+
},
253268
}
254269

255270
for _, tc := range testCases {

0 commit comments

Comments
 (0)