http.ErrContentLength
GoERRORNotableHTTP
http: wrote more than the declared Content-Length
Quick Answer
Set Content-Length only after computing the exact response size, or omit it and let the server use chunked encoding.
What this means
Returned when a handler writes more bytes than specified in the Content-Length header. The extra bytes are silently discarded by the server.
Why it happens
- 1Handler sets Content-Length header to a value smaller than the actual body
- 2Reusing a ResponseWriter after content has already been flushed
Fix
Buffer response before setting header
Buffer response before setting header
var buf bytes.Buffer
fmt.Fprintf(&buf, "hello")
w.Header().Set("Content-Length",
strconv.Itoa(buf.Len()))
w.Write(buf.Bytes())Why this works
Computing length from the buffer ensures Content-Length matches the actual body.
Code examples
Detectgo
_, err := w.Write(extra)
if errors.Is(err, http.ErrContentLength) {
log.Println("content-length mismatch")
}Buffer firstgo
var b bytes.Buffer
fmt.Fprint(&b, data)
w.Header().Set("Content-Length",
strconv.Itoa(b.Len()))Omit headergo
// Let HTTP/1.1 use chunked encoding fmt.Fprint(w, body)
Same error in other languages
Sources
Official documentation ↗
Go standard library
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev