valyala/fasthttp · error
cannot parse content-length: %w
Error message
cannot parse content-length: %w
What it means
parseContentLength failed because parseUintBuf could not read any valid unsigned integer from the Content-Length bytes (e.g. empty or starting with a non-digit). The underlying parse error is wrapped with this message.
Source
Thrown at header.go:3345
for i, n := 0, len(h.h); i < n; i++ {
kv := &h.h[i]
if caseInsensitiveCompare(kv.key, strCookie) {
h.cookies = parseRequestCookies(h.cookies, kv.value)
tmp := *kv
copy(h.h[i:], h.h[i+1:])
n--
i--
h.h[n] = tmp
h.h = h.h[:n]
}
}
h.cookiesCollected = true
}
func parseContentLength(b []byte) (int, error) {
v, n, err := parseUintBuf(b)
if err != nil {
return -1, fmt.Errorf("cannot parse content-length: %w", err)
}
if n != len(b) {
return -1, fmt.Errorf("cannot parse content-length: %w", ErrNonNumericChars)
}
return v, nil
}
type headerValueScanner struct {
b []byte
value []byte
}
func (s *headerValueScanner) next() bool {
b := s.b
if len(b) == 0 {
return false
}
before, after, ok := bytes.Cut(b, []byte{','})View on GitHub (pinned to c96f600972)
Solutions
- Send a plain decimal integer as Content-Length (e.g. 'Content-Length: 42').
- Use chunked transfer-encoding instead if the length is unknown.
- Fix the client/proxy that mangles the Content-Length value.
- Log the raw header at an early middleware to identify the offending producer.
Example fix
// before
req.Header.Set("Content-Length", "12 bytes")
// after
req.Header.Set("Content-Length", strconv.Itoa(len(body))) Defensive patterns
Strategy: validation
Validate before calling
func validContentLength(cl string) bool {
if cl == "" { return false }
for i := 0; i < len(cl); i++ { if cl[i] < '0' || cl[i] > '9' { return false } }
return true
} Try / catch
_, err := parseContentLength(b)
if err != nil && strings.Contains(err.Error(), "cannot parse content-length") {
// return 400 Bad Request with framing error
} Prevention
- Set Content-Length programmatically via strconv.Itoa(len(body))
- Never hard-code Content-Length strings
- Prefer chunked encoding when length is unknown
When it happens
Trigger: A Content-Length header whose value is empty or begins with a non-numeric character, e.g. 'Content-Length: ' or 'Content-Length: abc' or 'Content-Length: +12'.
Common situations: Hand-crafted or scripted HTTP requests with bad framing; proxy rewriting bugs truncating the value; fuzzing/scanning tools sending garbage framing headers.
Related errors
- fasthttp: need more data: cannot find trailing lf
- too large hex number
- fasthttp: no cookies found
- fasthttp: invalid cookie value
- fasthttp: contain forbidden trailer
AI-assisted analysis of valyala/fasthttp@c96f600972 (2026-08-31).
Data as JSON: /api/errors/e12297db1903156b.
Report an issue: GitHub.