1

I'm playing with Kitura. I have installed a single router endpoint that looks like:

let router = Router()

router.all() { _, response, next in
    response.headers["Content-Type"] = "application/json; charset=utf-8"
    next()
}

router.get("/hello") { _, response, next in
    response.send("{\"message\": \"Hello World\"}")
    next()
}

Kitura.addHTTPServer(onPort: 9143, with: router)
print("Application Server Starting...")
Kitura.run()

I'm really confused/frustrated by this next closure/callback parameter. Many (maybe outdated?) tutorials don't mention or include it, but if I don't call it, my router hangs and the client response is never sent.

Is there a way for me to avoid having to call this in my RouterHandler? Or have it called automatically? It seems a huge source of potential human error to need to manually execute this callback in every method, and it adds clutter. (Other frameworks like Spring Web execute the chain automatically, there's no next() call required.)

Craig Otis
  • 31,257
  • 32
  • 136
  • 234

1 Answers1

3

You can call response.end() when you're done sending the response and in that case you don't need to call next(). next() is used to provide flexibility so subsequent handlers can be invoked or skipped as needed.

But you raise a good point, it may be more intuitive to call next() automatically unless a flag is explicitly set to skip subsequent handlers and we will look into it. Thanks!

On looking into the code, it appears Kitura's fallback handling (which calls response.end() if it wasn't called by any of the handlers) is dependent on next() being invoked, which it really should not be. I'll put in a change to fix that. Thanks again for bringing this up.

Navneet
  • 81
  • 3
  • Ah, thanks - I will try this. I just found it odd that even tutorials on IBM's website don't include `.end()`, *or* the call to `next()`: https://developer.ibm.com/swift/2016/02/22/building-end-end-cloud-apps-using-swift-kitura/ – Craig Otis Feb 11 '17 at 16:55
  • We made a change to Kitura 1.6.1 that will end the response if all the handlers finish without ending it explicitly. This should prevent others from running into the issue you ran into. Thanks! – Navneet Feb 16 '17 at 14:57