guzba/mummy

custom notFoundHandler example

ITwrx opened this issue · 2 comments

ITwrx commented

it would be nice if the examples included one on how to make your own notFoundHandler as an example on how to override those handlers (500, etc). I see it's possible, but i'm not sure how to do it.

The Router* includes a couple of default handlers which you can override. See example for 404 in this PR: #99

You can see the implementation within the routers.nim with these public object items:

  • notFoundHandler
  • methodNotAllowedHandler
  • errorHandler

Each of these are just a normal RequestHandler. So just create their route and add them to the Router object:

proc customNotFound(request: Request) =
  const body = "<h1>I'm not here</h1>"

  var headers: httpheaders.HttpHeaders
  headers["Content-Type"] = "text/html"

  if request.httpMethod == "HEAD":
    headers["Content-Length"] = $body.len
    request.respond(404, headers)
  else:
    request.respond(404, headers, body)

var router: Router
router.notFoundHandler = customNotFound

Great. thanks!