httprouter is a popular routing middleware for Golang, which allows you to register custom handlers for specific routes or patterns. In cases where a route or resource is not found, you may want to handle these 404 Not Found responses yourself.
The httprouter.Router type has a field called NotFound, which is an http.Handler. This means that you can assign a custom handler to this field to handle 404 responses.
To create a custom NotFound handler, you need to define a function with the signature:
func(http.ResponseWriter, *http.Request)
You can then convert this function to an http.Handler using the http.HandlerFunc helper function.
Here is an example of how you can set a custom NotFound handler:
<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) w.Write([]byte("My own Not Found handler.")) w.Write([]byte(" The page you requested could not be found.")) } var router *httprouter.Router = ... // Your router value router.NotFound = http.HandlerFunc(MyNotFound)</code>
This custom handler will be automatically invoked by httprouter when a 404 Not Found response is encountered.
In some cases, you may want to manually invoke the NotFound handler from within another handler. You can achieve this by passing a ResponseWriter and a *Request to the MyNotFound function or directly to the router's NotFound method:
<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>
The above is the detailed content of How to Customize 404 Error Handling in httprouter with Custom Handlers?. For more information, please follow other related articles on the PHP Chinese website!