Go: http: superfluous response.WriteHeader call
net/http logs this when a handler writes the status twice. It almost always marks a later status write that was silently ignored, or no return.

Introduction & Quick Summary
The handler works, the client gets a response, and the server log still prints a line nobody asked for:
2026/11/28 07:00:12 http: superfluous response.WriteHeader call from main.handleOrder (handlers.go:64)
Quick answer: http.ResponseWriter accepts exactly one status line, sent by the first WriteHeader call or implicitly by the first Write. A second WriteHeader is ignored, and net/http logs this line to the server's error log so the mistake is visible instead of silent. Find the second call and make the handler return after the first one.
func handleOrder(w http.ResponseWriter, r *http.Request) {
order, err := loadOrder(r.Context(), r.PathValue("id"))
if err != nil {
http.Error(w, "not found", http.StatusNotFound) // writes header and body
return // without this, the next line writes again
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(order)
}The log names the function and file position of the offending call, usually enough to find it in seconds. The harder cases are middleware that wraps the writer and error paths that write a status and then fall through. This guide covers the writer's contract, the patterns that remove the line for good, and how to test for it.
Core Mechanics, Signatures & Reproducible Setup
The http.ResponseWriter interface has three methods: Header(), Write([]byte) and WriteHeader(statusCode int). The first write of either kind commits the response: headers are flushed, the status is fixed, and the body starts.
type ResponseWriter interface {
Header() Header
Write([]byte) (int, error)
WriteHeader(statusCode int)
}The rules that matter for this error:
- The first
WriteHeaderwins. Later calls are no-ops and produce the log line. Writebefore anyWriteHeadersends200 OKimplicitly, so a laterWriteHeader(500)arrives too late.http.ErrorcallsWriteHeaderitself, so following it with another write or status is the classic double call.
A reproducible server that prints the line on every request:
package main
import (
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("hello")) // fine
w.WriteHeader(http.StatusInternalServerError) // superfluous, logged
})
http.ListenAndServe(":8080", nil)
}go run main.go &
curl -i http://localhost:8080/
# HTTP/1.1 200 OK
# hello
# server log: http: superfluous response.WriteHeader call from main.main.func1 (main.go:11)The client sees 200 and hello; the second status never reaches it, which is why the bug hides in manual testing and shows up in logs.
Key Comparison Table
| Call order | Status sent | Log line | Result |
|---|---|---|---|
WriteHeader(200) then Write | 200 | no | normal response |
Write then WriteHeader(500) | 200 | yes | client sees success |
WriteHeader(500) twice | 500 | yes | harmless but noisy |
http.Error then Write | 500 plus body | yes | duplicated body text |
WriteHeader after Flush | status already sent | yes | late status lost |
WriteHeader on hijacked connection | none | yes | connection owned by caller |
| Pattern | How the status is written | Risk |
|---|---|---|
| early return | once, in the failing branch | none if every branch returns |
| single exit point | once, from a status variable | needs discipline |
| wrapper recording status | delegates to the real writer | double call if written twice |
http.Error helper | header plus plain-text body | caller must return |
| template execution | writes 200 on first byte | errors after that cannot change status |
| Symptom | Likely cause | Fix |
|---|---|---|
| log line but correct response | second status ignored | delete the extra call |
| client sees 200 for a failure | error path wrote body first | write status before body |
| duplicated error message | http.Error then another write | return after http.Error |
| 200 in logs, 500 to client | logging happens after handler returns | log from the wrapper once |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Error paths that fall through
The most common shape is a guard that writes an error and forgets to stop:
func handle(w http.ResponseWriter, r *http.Request) {
var body Payload
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
// missing return
}
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(body)
}The client receives 400 with bad request followed by 201's body appended, because the status was already committed. The fix is one return.
2. Wrapping the writer to record the status
Middleware that logs status codes must record WriteHeader without changing behaviour:
type statusRecorder struct {
http.ResponseWriter
status int
}
func (r *statusRecorder) WriteHeader(code int) {
if r.status == 0 {
r.status = code
r.ResponseWriter.WriteHeader(code)
}
}
func (r *statusRecorder) Write(b []byte) (int, error) {
if r.status == 0 {
r.status = http.StatusOK
}
return r.ResponseWriter.Write(b)
}
func withStatus(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rec := &statusRecorder{ResponseWriter: w}
next.ServeHTTP(rec, r)
log.Printf("%s %s -> %d", r.Method, r.URL.Path, rec.status)
})
}Two details keep this from creating new problems: the wrapper must forward Flush by implementing http.Flusher and delegating when the handler streams, and it must not call WriteHeader itself before next runs.
3. http.Error already wrote the header
http.Error sets Content-Type: text/plain; charset=utf-8, adds X-Content-Type-Options: nosniff, writes the status, then writes the message. Calling it after setting JSON headers discards those headers, and calling it after a write produces the log line:
// wrong: header set, then thrown away by http.Error
w.Header().Set("Content-Type", "application/json")
http.Error(w, `{"error":"not found"}`, http.StatusNotFound)
// right: JSON error response
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode(map[string]string{"error": "not found"})For APIs, a small writeJSON helper with the status as a parameter keeps both branches consistent. Checking the status code a client actually received is easier with curl -i; the curl command generator builds the request, and the HTTP status code reference confirms which code belongs to which failure.
4. Streaming responses lock the status in
Once a handler flushes, the status is final. A failure after the first flush cannot be reported with an error code:
func stream(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(http.StatusOK)
for _, line := range lines(r.Context()) {
if _, err := fmt.Fprintf(w, "data: %s\n\n", line); err != nil {
log.Printf("stream aborted: %v", err) // cannot change the status now
return
}
flusher.Flush()
}
}Design streaming handlers so errors that matter happen before the first byte, and log the rest. Sending an error event inside the stream is the only way to tell the client after the fact.
5. Hijacked connections and WebSockets
After Hijack, the handler owns the raw connection and net/http no longer manages the response, so a later WriteHeader logs a different line and has no effect:
func upgrade(w http.ResponseWriter, r *http.Request) {
hj, ok := w.(http.Hijacker)
if !ok {
http.Error(w, "no hijack", http.StatusInternalServerError)
return
}
conn, buf, err := hj.Hijack()
if err != nil {
return // do not write to w after this
}
defer conn.Close()
buf.WriteString("HTTP/1.1 101 Switching Protocols\r\n\r\n")
buf.Flush()
}6. Catch the line in tests
httptest.ResponseRecorder does not run the server's logging, so it will not show the message. Point the test server's ErrorLog at a buffer and assert it stays empty:
func TestNoDoubleWriteHeader(t *testing.T) {
var logs bytes.Buffer
srv := httptest.NewUnstartedServer(mux())
srv.Config.ErrorLog = log.New(&logs, "", 0)
srv.Start()
defer srv.Close()
res, err := http.Get(srv.URL + "/orders/missing")
if err != nil {
t.Fatal(err)
}
res.Body.Close()
if strings.Contains(logs.String(), "superfluous") {
t.Fatalf("double WriteHeader: %s", logs.String())
}
}A test like this turns a log line nobody reads into a failing build.
Common Compilation/Runtime Mistakes & Version Gotchas
- Writing the body before the status.
Writecommits200, so the laterWriteHeader(4xx)is both superfluous and wrong; set the header first. - Ignoring
Writeerrors. A client that disconnected makesWritereturn an error; the status is already sent, so log and stop rather than retry the response. - Assuming the client saw both statuses. Only the first is transmitted, so a client parses a success body for a failed request.
- Copying a
ResponseWriterby value. A wrapper that embeds it and adds fields must be used through a pointer, or the recorded status is lost. - Version notes.
net/httphas logged this warning for years; Go 1.22 addedRequest.PathValueand the enhancedServeMuxpatterns used above. The log goes toServer.ErrorLog, which defaults to the standard logger, so a custom logger will not see it unless it is assigned. - Middleware order. A middleware that writes an error and calls
nextanyway produces the same message from another file; read the function name in the log first.
Official documentation: net/http ResponseWriter and Effective Go.
Official references
primary documentationThe Go documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Go guides
All Go guidesGo: x509 certificate signed by unknown authority
Go cannot build a chain to a trusted root: no CA bundle in the image, a private CA, or a missing intermediate. Install roots or set RootCAs.
Go: fatal error: concurrent map writes in goroutines
The runtime catches two writes to one map and stops the process. Guard access with a mutex, use sync.Map for caches, or give one owner.
Go: import cycle not allowed
Go forbids cycles in the package import graph. Break them by extracting shared types, declaring interfaces where consumed, or inverting init registration.
Go: declared and not used compile error
Go rejects unused local variables and imports on purpose. Delete dead declarations, handle err values and keep imports honest instead of blanking them.
More in Go
All Go guidesThe guides filed next to this one in Go, in library order.