Implementing Custom 404 Error Pages Using the Net/HTTP Package
When a user navigates to a non-existent URL, the default behavior in web servers is to display a generic "404 Page Not Found" message. To enhance user experience, you may want to create a custom 404 page that provides more information or redirects users to a relevant destination.
In this scenario, with the simplified code provided:
package main import ( "fmt" "net/http" ) func main() { http.HandleFunc("/", homeHandler) http.HandleFunc("/smth/", smthHandler) http.ListenAndServe(":12345", nil) } func homeHandler(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { errorHandler(w, r, http.StatusNotFound) return } fmt.Fprint(w, "welcome home") } func smthHandler(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/smth/" { errorHandler(w, r, http.StatusNotFound) return } fmt.Fprint(w, "welcome smth") } func errorHandler(w http.ResponseWriter, r *http.Request, status int) { w.WriteHeader(status) if status == http.StatusNotFound { fmt.Fprint(w, "custom 404") } }
The errorHandler function, which is used to handle all HTTP errors, can be customized to display a custom 404 error page by returning the http.StatusNotFound error code and writing the desired content to the ResponseWriter.
In this example, the errorHandler function returns a custom message "custom 404" when a 404 error status is detected. This allows you to replace the default "404 Page Not Found" message with a more user-friendly and informative page.
Additionally, the errorhandler function can be extended to catch other HTTP errors and implement custom error handling, such as logging errors, sending email notifications, or redirecting users to a specific error page.
The above is the detailed content of How to Implement Custom 404 Error Pages in Go using the `net/http` Package?. For more information, please follow other related articles on the PHP Chinese website!