Home > Backend Development > Golang > How to Customize Error Handling in Go's HTTP Package?

How to Customize Error Handling in Go's HTTP Package?

Linda Hamilton
Release: 2024-12-22 14:48:14
Original
682 people have browsed it

How to Customize Error Handling in Go's HTTP Package?

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")
    }
}
Copy after login

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)
Copy after login

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)
}
Copy after login

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")
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template