How do I use middleware to recover from panics in Go?

In Go, you can use middleware to recover from panics that may occur during the execution of HTTP handlers. This allows your application to handle errors gracefully without crashing the server. Below is an example of how you can implement a middleware function that recovers from panics and logs the error.

package main import ( "log" "net/http" "recover" ) // Recovery middleware func Recovery(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer func() { if err := recover(); err != nil { log.Println("Recovered from panic:", err) http.Error(w, "Internal Server Error", http.StatusInternalServerError) } }() next.ServeHTTP(w, r) }) } func main() { // Example of a simple handler helloHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { panic("Something went wrong!") }) http.Handle("/", Recovery(helloHandler)) log.Println("Starting server on :8080...") log.Fatal(http.ListenAndServe(":8080", nil)) }

Go Middleware Recover from Panic HTTP Handlers Error Handling Logging Go Web Development