Home >Backend Development >Golang >How Can I Customize 404 Error Pages Using Go's Standard HTTP Package?

How Can I Customize 404 Error Pages Using Go's Standard HTTP Package?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-19 04:52:09957browse

How Can I Customize 404 Error Pages Using Go's Standard HTTP Package?

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:

  1. Define a separate error handling function:
func errorHandler(w http.ResponseWriter, r *http.Request, status int)
  1. Inside the error handler, set the appropriate HTTP status code and generate the desired error response (e.g., "custom 404").
  2. Within each handler function, check if the requested URL matches the expected pattern. If not, invoke the error handler with the correct HTTP status code.

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!

Statement:
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