Customizing 404 Error Pages with the Standard HTTP Package
When accessing an incorrect URL, browsers typically display a generic "404 page not found" message. Customizing this response with a tailored error page can enhance the user experience.
Using the HTTP Package
For applications utilizing the standard net/http package, the following steps can be taken to implement a custom 404 page:
func errorHandler(w http.ResponseWriter, r *http.Request, status int)
For example, the following code checks for the root URL ("/") and a specific sub-path ("/smth/"). Any other URLs will trigger the custom 404 error page:
func homeHandler(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { errorHandler(w, r, http.StatusNotFound) return } // Handle root URL request } func smthHandler(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/smth/" { errorHandler(w, r, http.StatusNotFound) return } // Handle "/smth/" sub-path request } // Custom error handler func errorHandler(w http.ResponseWriter, r *http.Request, status int) { w.WriteHeader(status) if status == http.StatusNotFound { fmt.Fprint(w, "custom 404") } }
This approach provides greater flexibility in customizing error pages for specific scenarios.
The above is the detailed content of How Can I Customize 404 Error Pages Using Go's Standard HTTP Package?. For more information, please follow other related articles on the PHP Chinese website!