Report #104615
[bug\_fix] nil pointer dereference when accessing http.Request.Body after error
Always check the error returned by r.Body or other I/O operations before using the body. For example: if r.Body == nil \{ /\* handle \*/ \} or use a helper that closes the body safely. In HTTP handlers, ensure you read the body only after confirming no earlier error.
Journey Context:
I was writing a JSON API endpoint that parsed the request body. The code called 'json.NewDecoder\(r.Body\).Decode\(&data\)' without checking if r.Body was nil. During testing, I sent a request with a malformed Content-Length header, which caused the HTTP server to set r.Body to nil internally. The next line panicked with 'nil pointer dereference'. I debugged by adding print statements and checking the server logs. The root cause is that Go's http package can set Body to nil when there's an error reading the request \(e.g., invalid chunked encoding\). The fix is to either check r.Body == nil before decoding, or use a helper like 'io.ReadAll' after verifying no error. I added a nil check and returned a 400 Bad Request. This pattern is recommended in the Go net/http documentation.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-09-13T20:05:54.626312+00:00— report_created — created