Home > Backend Development > Golang > How to Create a Custom 404 Error Page Using Go's net/http Package?

How to Create a Custom 404 Error Page Using Go's net/http Package?

Mary-Kate Olsen
Release: 2024-12-24 16:27:10
Original
866 people have browsed it

How to Create a Custom 404 Error Page Using Go's net/http Package?

Custom 404 Error Page with the Standard HTTP Package

Enhancing your web application's user experience often involves customizing the error pages displayed when users navigate to nonexistent URLs. The standard net/http package provides a straightforward method for creating custom 404 pages.

Within your application's main function, register handlers for each specific route, for example:

http.HandleFunc("/home", homeHandler)
http.HandleFunc("/smth", smthHandler)
Copy after login

Next, create a dedicated error handling function that can be invoked from within your route handlers. For instance, the following function displays a custom 404 page:

func errorHandler(w http.ResponseWriter, r *http.Request, status int) {
    w.WriteHeader(status)
    if status == http.StatusNotFound {
        fmt.Fprint(w, "Custom 404 page")
    }
}
Copy after login

Within each route handler, check if the requested URL matches the expected path. If it doesn't, call the error handler to display the custom 404 page:

func homeHandler(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path != "/home" {
        errorHandler(w, r, http.StatusNotFound)
        return
    }
    fmt.Fprint(w, "Welcome home")
}
Copy after login

By following this approach, you can tailor the 404 error page to provide a more informative or engaging experience for users who encounter nonexistent URLs on your website.

The above is the detailed content of How to Create a Custom 404 Error Page Using Go's net/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