Skip to Content
Skip to content
Recover From Panics and Cap Request Bodies in Go HTTP Middleware
Advanced
Tutorials

Recover From Panics and Cap Request Bodies in Go HTTP Middleware

Keep one handler panic or one oversized JSON payload from crashing a Go API server using recover middleware and http.MaxBytesReader. After this, broken requests return clean 413 and 500 JSON responses while the server stays up.

Updated 5 min read GoWeb Services

In Go's net/http server, a panic inside a single request handler does not terminate the whole process—net/http catches it internally—but it drops the client's TCP connection without sending a status code or JSON error body. Meanwhile, an uncapped json.NewDecoder(r.Body).Decode(...) happily reads a 500 MB upload straight into heap memory until Kubernetes kills the pod with OOMKilled.

Two standard-library guards fix both gaps cleanly: an outer recover() middleware returning structured 500 JSON, and http.MaxBytesReader returning clean 413 Payload Too Large rejections. Verified on Go 1.27.

Case 1: Panic recovery middleware + capped JSON bodies

Notice how http.MaxBytesReader(w, r.Body, 1024) wraps r.Body and returns a typed *http.MaxBytesError when the client exceeds 1,024 bytes—letting your handler return 413 instead of a generic 400:

package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"
)

func recoverMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if rec := recover(); rec != nil {
				if rec == http.ErrAbortHandler {
					panic(rec)
				}
				w.Header().Set("Content-Type", "application/json")
				w.WriteHeader(http.StatusInternalServerError)
				_, _ = w.Write([]byte(`{"error":"internal server error"}`))
			}
		}()
		next.ServeHTTP(w, r)
	})
}

func createItem(w http.ResponseWriter, r *http.Request) {
	r.Body = http.MaxBytesReader(w, r.Body, 1024)
	var body struct{ Name string `json:"name"` }
	if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
		var maxErr *http.MaxBytesError
		if errors.As(err, &maxErr) {
			http.Error(w, `{"error":"payload too large"}`, http.StatusRequestEntityTooLarge)
			return
		}
		http.Error(w, `{"error":"invalid json"}`, http.StatusBadRequest)
		return
	}
	w.WriteHeader(http.StatusCreated)
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/boom", func(w http.ResponseWriter, r *http.Request) { panic("nil lookup") })
	mux.HandleFunc("/items", createItem)
	h := recoverMiddleware(mux)

	rec1 := httptest.NewRecorder()
	h.ServeHTTP(rec1, httptest.NewRequest(http.MethodGet, "/boom", nil))
	fmt.Printf("boom status=%d body=%s\n", rec1.Code, rec1.Body.String())

	big := bytes.Repeat([]byte("a"), 2048)
	req := httptest.NewRequest(http.MethodPost, "/items", bytes.NewReader(append([]byte(`{"name":"`), append(big, []byte(`"}`)...)...)))
	rec2 := httptest.NewRecorder()
	h.ServeHTTP(rec2, req)
	fmt.Printf("big status=%d body=%s", rec2.Code, rec2.Body.String())
}
$ go run .
boom status=500 body={"error":"internal server error"}
big status=413 body={"error":"payload too large"}

Case 2: Log debug.Stack() and re-panic http.ErrAbortHandler

Two production details matter in real recovery middleware:

  • Always log rec and string(debug.Stack()) server-side with slog.Error: Never swallow a panic silently (or you lose all visibility into the bug), and never print the Go stack trace into the HTTP response body (which leaks internal file paths and secrets to clients).
  • Re-panic on http.ErrAbortHandler: Streaming handlers intentionally call panic(http.ErrAbortHandler) to abort a broken response silently—re-panicking lets net/http close the connection cleanly without writing a fake 500.

Case 3: Why child goroutines bypass recoverMiddleware

recover() only catches panics occurring on the exact same goroutine where defer recover() was registered. If a handler launches a fire-and-forget goroutine (go sendAuditEvent(user)) and that child goroutine hits a nil pointer panic, recoverMiddleware on the request goroutine never sees it—the entire Go server crashes immediately! Wrap background goroutines with their own defer recover() too.

Case 4: Why http.MaxBytesReader beats io.LimitReader on HTTP bodies

Unlike io.LimitReader (which quietly returns io.EOF and truncates), http.MaxBytesReader(w, r.Body, limit) returns a typed *http.MaxBytesError and tells the net/http server to close the TCP connection instead of wasting bandwidth draining a 500 MB attack payload.

💡 Tip

Place recoverMiddleware as the outermost wrapper around your router—outside logging and auth—so a panic anywhere in the middleware chain still logs and returns a structured 500 JSON response.

Common mistakes

  • Swallowing panics without logging debug.Stack(): Hides nil-pointer bugs behind silent 500 responses.
  • Calling w.WriteHeader(500) after the handler already wrote part of a 200 body: Once headers are flushed on the wire, net/http ignores a second status code—still log the stack trace cleanly instead of corrupting the output with raw panic text.
  • Leaving json.NewDecoder(r.Body) uncapped on public POST routes: Lets one client trigger an OOM kill for every user on that server.

⚠ Warning

Do not rely on recover() for ordinary error handling (like missing rows or invalid JSON). Reserve panics for programmer bugs; use explicit error returns for expected failures.

What happens if you skip this

Without MaxBytesReader, one giant malicious upload can OOM-kill your container; without recovery middleware, handler panics drop TCP connections mid-response with zero structured error details.

Related course: Go Advanced.

About

Keep one handler panic or one oversized JSON payload from crashing a Go API server using recover middleware and http.MaxBytesReader. After this, broken requests return clean 413 and 500 JSON responses while the server stays up.

Responsible
Jay P
Last Update
11/27/2026
Reading Time
5 min
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.