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)).