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))
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?