I'm using httprouter
for an API and I'm trying to work out how to handle 404s. It does say in the docs that 404's can be handled manually but I don't really have an idea how to write my own custom handler.
I've tried the following after my other routes...
router.NotFound(pageNotFound)
But I get the error not enough arguments in call to router.NotFound
.
If anyone could point me in the right direction it would be great.
NotFound is a function pointer of type http.HandlerFunc. You will have to put a function with the signature
Func(w ResponseWriter, r *Request)
somewhere and assign it to NotFound (router.NotFound = Func
).The type
httprouter.Router
is astruct
which has a field:So type of
NotFound
ishttp.Handler
, an interface type which has a single method:If you want your own custom "Not Found" handler, you have to set a value that implements this interface.
The easiest way is to define a function with signature:
And use the
http.HandlerFunc()
helper function to "convert" it to a value that implements thehttp.Handler
interface, whoseServeHTTP()
method simply calls the function with the above signature.For example:
This
NotFound
handler will be invoked by thehttprouter
package. If you would want to call it manually from one of your other handlers, you would have to pass aResponseWriter
and a*Request
to it, something like this: