Custom Error Handling in the Standard HTTP Package
In Golang's standard HTTP package, when an incorrect URL is accessed, a default "404 page not found" message is typically displayed. To customize this response and provide a more user-friendly experience, you can implement your own error handling function.
Solution for Pure HTTP Package:
If you're using the net/http package alone, you can create a dedicated errorHandler function:
func errorHandler(w http.ResponseWriter, r *http.Request, status int) { w.WriteHeader(status) if status == http.StatusNotFound { fmt.Fprint(w, "custom 404") } }
Then, you can register your custom handlers and the errorHandler as shown in the provided code:
http.HandleFunc("/", homeHandler) http.HandleFunc("/smth/", smthHandler) http.ListenAndServe(":12345", nil)
Solution for Gorilla/Mux Router:
If you're using the gorilla/mux router, you can leverage its built-in feature to handle not-found scenarios:
func main() { r := mux.NewRouter() r.NotFoundHandler = http.HandlerFunc(notFound) }
You'll then need to implement the notFound function as desired:
func notFound(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) fmt.Fprint(w, "custom 404") }
Enhanced Error Handling:
The provided code example demonstrates basic error handling, but you can extend this to handle various HTTP errors and perform additional actions, such as logging or sending notifications.
The above is the detailed content of How to Customize Error Handling in Go's HTTP Package?. For more information, please follow other related articles on the PHP Chinese website!