Home  >  Article  >  Backend Development  >  How to Custom Handle 404 Errors with HTTP Router?

How to Custom Handle 404 Errors with HTTP Router?

Susan Sarandon
Susan SarandonOriginal
2024-10-26 11:39:30561browse

How to Custom Handle 404 Errors with HTTP Router?

Handling 404s with HTTP Router

The HTTP Router library provides robust routing capabilities for API development. One common task is handling 404 (Not Found) responses. While the documentation briefly mentions the possibility of defining a custom 404 handler, the implementation details can be confusing.

Understanding the Custom Handler Interface

The httprouter.Router struct contains a field named NotFound, which is an http.Handler interface. This interface defines a single method, ServeHTTP(), which takes a ResponseWriter and a Request as arguments.

Creating a Custom 404 Handler

To create a custom 404 handler, define a function with the ServeHTTP() method signature and use the http.HandlerFunc() helper function to convert it into an http.Handler value.

Example Implementation:

<code class="go">func MyNotFound(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/plain; charset=utf-8")
    w.WriteHeader(http.StatusNotFound) // StatusNotFound = 404
    w.Write([]byte("My own Not Found handler."))
    w.Write([]byte(" The page you requested could not be found."))
}</code>

Setting the Custom Handler

Next, assign your custom handler to the NotFound field of the HTTP Router object:

<code class="go">router := httprouter.New()
router.NotFound = http.HandlerFunc(MyNotFound)</code>

Manual Invocation of Custom Handler

If you ever need to manually invoke your custom 404 handler from within another HTTP handler, you can do so by passing it a ResponseWriter and a Request:

<code class="go">func ResourceHandler(w http.ResponseWriter, r *http.Request) {
    exists := ... // Check for resource existence
    if !exists {
        MyNotFound(w, r) // Pass ResponseWriter and Request
        return
    }

    // Resource exists, serve it
    // ...
}</code>

The above is the detailed content of How to Custom Handle 404 Errors with HTTP Router?. 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