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

Fix superfluous writing header after flush in otelhttp #6074

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm

### Fixed

- Superfluous call to `WriteHeader` when flushing after setting a status code in `go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp`. (#6074)
- Superfluous call to `WriteHeader` when writing the response body after setting a status code in `go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp`. (#6055)

<!-- Released section -->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,12 @@ func (w *RespWriterWrapper) writeHeader(statusCode int) {

// Flush implements [http.Flusher].
func (w *RespWriterWrapper) Flush() {
w.WriteHeader(http.StatusOK)
w.mu.Lock()
defer w.mu.Unlock()

if !w.wroteHeader {
w.writeHeader(http.StatusOK)
}

if f, ok := w.ResponseWriter.(http.Flusher); ok {
f.Flush()
Expand Down
23 changes: 23 additions & 0 deletions instrumentation/net/http/otelhttp/test/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,12 @@ func (rw *respWriteHeaderCounter) WriteHeader(statusCode int) {
rw.ResponseWriter.WriteHeader(statusCode)
}

func (rw *respWriteHeaderCounter) Flush() {
if f, ok := rw.ResponseWriter.(http.Flusher); ok {
f.Flush()
}
}

func TestHandlerPropagateWriteHeaderCalls(t *testing.T) {
testCases := []struct {
name string
Expand Down Expand Up @@ -265,6 +271,23 @@ func TestHandlerPropagateWriteHeaderCalls(t *testing.T) {
},
expectHeadersWritten: []int{http.StatusBadRequest},
},
{
name: "When writing the header indirectly through flush",
handler: func(w http.ResponseWriter, r *http.Request) {
f := w.(http.Flusher)
f.Flush()
},
expectHeadersWritten: []int{http.StatusOK},
},
{
name: "With a header already written when flushing",
handler: func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
f := w.(http.Flusher)
f.Flush()
},
expectHeadersWritten: []int{http.StatusBadRequest},
},
}

for _, tc := range testCases {
Expand Down
Loading