Configure httprouter for NotNound

I use httprouterfor the API and I am trying to figure out how to handle 404s. He says in docs that 404 can be handled manually, but I have no idea how to write my own custom handler .

I tried the following after my other routes ...

router.NotFound(pageNotFound)

But I get an error message not enough arguments in call to router.NotFound.

If someone could point me in the right direction, that would be great.

+4
source share
2 answers

A type httprouter.Routeris one structthat has a field:

NotFound http.HandlerFunc

So, NotFoundis http.HandlerFunca function type with a signature:

type HandlerFunc func(ResponseWriter, *Request)

"Not Found", .

:

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."))
    w.Write([]byte(" The page you requested could not be found."))
}

var router *httprouter.Router = ... // Your router value
router.NotFound = MyNotFound

NotFound httprouter. , ResponseWriter *Request, - :

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
    // ...
}
+6

NotFound - http.HandlerFunc. Func(w ResponseWriter, r *Request) - NotFound (router.NotFound = Func).

+1

All Articles