Home  >  Article  >  Backend Development  >  How to Customize HTTP 404 Error Handling in Go with HTTProuter?

How to Customize HTTP 404 Error Handling in Go with HTTProuter?

Susan Sarandon
Susan SarandonOriginal
2024-10-26 13:56:31474browse

How to Customize HTTP 404 Error Handling in Go with HTTProuter?

Customizing HTTP 404 Handling with HTTProuter

HTTProuter provides the ability to handle 404 responses manually. To achieve this, a custom handler function must be defined.

HTTProuter's Router struct possesses a NotFound field of type http.Handler. The http.Handler interface defines a single method, ServeHTTP(ResponseWriter, *Request). Hence, a custom handler must implement this function.

To create a custom handler, define a function with the signature func(http.ResponseWriter, *http.Request). Convert this function to an http.Handler value using the http.HandlerFunc() helper function. For instance:

<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) // Set status to 404
    w.Write([]byte("My NotFound handler"))
}

router.NotFound = http.HandlerFunc(MyNotFound)</code>

This custom handler will be triggered by HTTProuter. Alternatively, it can be invoked manually from other handlers by passing the ResponseWriter and *Request instances:

<code class="go">func ResourceHandler(w http.ResponseWriter, r *http.Request) {
    if ... { // Check for resource availability
        router.NotFound(w, r)
        return
    }
    // ... Serve the resource
}</code>

The above is the detailed content of How to Customize HTTP 404 Error Handling in Go with HTTProuter?. 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