Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readGo
#go#net-http#responsewriter#logging
Bold white headline reading WRITEHEADER TWICE beside a cyan response crate with two amber status plates.

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.

go
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.

go
type ResponseWriter interface { Header() Header Write([]byte) (int, error) WriteHeader(statusCode int) }

The rules that matter for this error:

  • The first WriteHeader wins. Later calls are no-ops and produce the log line.
  • Write before any WriteHeader sends 200 OK implicitly, so a later WriteHeader(500) arrives too late.
  • http.Error calls WriteHeader itself, so following it with another write or status is the classic double call.

A reproducible server that prints the line on every request:

go
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 orderStatus sentLog lineResult
WriteHeader(200) then Write200nonormal response
Write then WriteHeader(500)200yesclient sees success
WriteHeader(500) twice500yesharmless but noisy
http.Error then Write500 plus bodyyesduplicated body text
WriteHeader after Flushstatus already sentyeslate status lost
WriteHeader on hijacked connectionnoneyesconnection owned by caller
PatternHow the status is writtenRisk
early returnonce, in the failing branchnone if every branch returns
single exit pointonce, from a status variableneeds discipline
wrapper recording statusdelegates to the real writerdouble call if written twice
http.Error helperheader plus plain-text bodycaller must return
template executionwrites 200 on first byteerrors after that cannot change status
SymptomLikely causeFix
log line but correct responsesecond status ignoreddelete the extra call
client sees 200 for a failureerror path wrote body firstwrite status before body
duplicated error messagehttp.Error then another writereturn after http.Error
200 in logs, 500 to clientlogging happens after handler returnslog 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:

go
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:

go
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:

go
// 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:

go
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:

go
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:

go
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. Write commits 200, so the later WriteHeader(4xx) is both superfluous and wrong; set the header first.
  • Ignoring Write errors. A client that disconnected makes Write return 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 ResponseWriter by value. A wrapper that embeds it and adds fields must be used through a pointer, or the recorded status is lost.
  • Version notes. net/http has logged this warning for years; Go 1.22 added Request.PathValue and the enhanced ServeMux patterns used above. The log goes to Server.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 next anyway 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 documentation

The Go documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Go guides

More in Go

All Go guides

The guides filed next to this one in Go, in library order.