Panic recovery middleware for HTTP servers

6723
0

Even in Go, panics happen: a nil pointer in an edge case, a bad slice index, or a library bug. I don't want a single request to take down the whole process, so I wrap handlers with a recovery middleware that captures panics, logs them with request context, and returns a safe 500. The important detail is to keep the response body generic (don't leak internals) while still capturing enough debug information in logs. I also attach a request_id header so a customer report can be tied to a specific failure. This middleware is not a replacement for tests, but it turns catastrophic crashes into contained errors and buys you time to ship a fix without burning a whole deploy.