How to Implement Recovery (Panic Catch) Middleware in Go

Web
Implement panic recovery middleware in Go by wrapping handlers with a defer-recover block to catch errors and return 500 responses.

Wrap your HTTP handler in a middleware function that calls recover() to catch panics and return a 500 status code instead of crashing the server.

func RecoveryMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if err := recover(); err != nil {
				log.Printf("panic recovered: %v", err)
				http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			}
		}()
		next.ServeHTTP(w, r)
	})
}

Apply it to your server with http.ListenAndServe(":8080", RecoveryMiddleware(yourHandler)).