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

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

Susan Sarandon
Release: 2024-10-26 13:56:31
Original
554 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template