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)
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") } }
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") }
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!