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

net/http/httptest: ensure that a superfluous WriteHeader call panics in httptest #69440

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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 src/net/http/httptest/recorder.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ func checkWriteHeaderCode(code int) {
// WriteHeader implements [http.ResponseWriter].
func (rw *ResponseRecorder) WriteHeader(code int) {
if rw.wroteHeader {
panic(fmt.Sprintf("superfluous response.WriteHeader call"))
return
}

Expand Down
21 changes: 17 additions & 4 deletions src/net/http/httptest/recorder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,6 @@ func TestRecorder(t *testing.T) {
"first code only",
func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(201)
w.WriteHeader(202)
w.Write([]byte("hi"))
},
check(hasStatus(201), hasContents("hi")),
Expand All @@ -147,8 +146,6 @@ func TestRecorder(t *testing.T) {
"write sends 200",
func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hi first"))
w.WriteHeader(201)
w.WriteHeader(202)
},
check(hasStatus(200), hasContents("hi first"), hasFlush(false)),
},
Expand All @@ -168,7 +165,6 @@ func TestRecorder(t *testing.T) {
"flush",
func(w http.ResponseWriter, r *http.Request) {
w.(http.Flusher).Flush() // also sends a 200
w.WriteHeader(201)
},
check(hasStatus(200), hasFlush(true), hasContentLength(-1)),
},
Expand Down Expand Up @@ -369,3 +365,20 @@ func TestRecorderPanicsOnNonXXXStatusCode(t *testing.T) {
})
}
}

// Ensure that httptest.Recorder panics when using WriteHeader twice.
func TestRecorderPanicsOnSuperfluousWriteHeader(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Fatal("Expected a panic")
}
}()

handler := func(rw http.ResponseWriter, _ *http.Request) {
rw.WriteHeader(200)
rw.WriteHeader(201)
}
r, _ := http.NewRequest("GET", "http://example.org/", nil)
rw := NewRecorder()
handler(rw, r)
}