Handling 404 Errors with httprouter's Custom Handlers
In an HTTP API built with httprouter, handling 404 (Not Found) errors requires a custom handler. The documentation mentions this possibility, but it doesn't provide explicit instructions on how to create one.
Setting Up a Custom Handler
To handle 404 errors manually, follow these steps:
Define a function with the following signature:
<code class="go">func(http.ResponseWriter, *http.Request)</code>
Convert the function into an http.Handler using the http.HandlerFunc() helper function.
<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.")) // or with more detailed message w.Write([]byte(" The page you requested could not be found.")) }</code>
Assign the MyNotFound handler to the NotFound field of the httprouter:
<code class="go">var router *httprouter.Router = ... // Your router value router.NotFound = http.HandlerFunc(MyNotFound)</code>
Manually Invoking the Custom Handler
In your handlers, you can manually call the MyNotFound handler, if needed, by passing the ResponseWriter and *Request:
<code class="go">func ResourceHandler(w http.ResponseWriter, r *http.Request) { exists := ... // Find out if requested resource is valid and available if !exists { MyNotFound(w, r) // Pass ResponseWriter and Request // Or via the Router: // router.NotFound(w, r) return } // Resource exists, serve it // ... }</code>
By implementing these steps, you can effectively handle 404 errors in your httprouter-based API and customize the behavior as needed.
The above is the detailed content of How to Handle 404 Errors with Custom Handlers in httprouter?. For more information, please follow other related articles on the PHP Chinese website!