Responses can accept multiple handlers allowing logic to be broken up into sections.
router.get("foo", handler: { request, response, next in
if request.queryParameters["bar"] == nil {
response.error = NSError(domain: "RouterTestDomain", code: 1, userInfo: [:])
}
next()
}, { request, response, next in
// Only gets called if no error
})
Multiple HTTP verbs can be specified for one path using the route method.
router.route("foo")
.get() { request, response, next in
// Get logic here
}
.post() { request, response, next in
// Post logic here
}
A large router can be broken up into sub-routers and be mounted under a path prefix. These sub-routers can even be placed in separate files.
let subrouter = Router()
subrouter.get("/") { _, response, _ in
try response.send("Hello from subsection").end()
}
subrouter.get("/about") {_, response, _ in
try response.send("About the subsection").end()
}
let mainRouter = Router()
mainRouter.get("/") {_, response, _ in
try response.send("Welcome").end()
}
mainRouter.all("sub", middleware: subrouter)
// Add HTTP Server to listen on port 8080
Kitura.addHTTPServer(onPort: 8080, with: mainRouter)
// start the framework - the servers added until now will start listening
Kitura.run()
A GET request to localhost:8080 will return “Welcome” and a request to localhost:8080/sub will return “Hello from subsection”