Reputation: 529
I have many URI for same resource in Ktor. To avoid to repeat too many lines, I found this solution:
routing {
get("/", home())
get("/index", home())
get("/home", home())
...
}
private fun home(): suspend PipelineContext<Unit, ApplicationCall>.(Unit) -> Unit =
{
val parameters = ...
call.respond(ThymeleafContent("/index.html", parameters))
}
Is there more elegant solution like this:
routing {
get("/", "/index", "/home") {
val parameters = ...
call.respond(ThymeleafContent("/index.html", parameters))
}
...
}
Upvotes: 0
Views: 656
Reputation: 8457
The only way I know of compressing that would be to create a global variable containing the home-paths and then forEach
it.
val homePaths = arrayOf("/path1", "/path2", ...)
...
routing {
homePaths.forEach { path -> get(path, home()) }
}
A cool feature would be to be able to specify a regular expression as the input of the routing method.
And something that you can cook for yourself is a KTX that does such thing.
fun Routing.get(varargs routes: String, call: suspend PipelineContext<Unit, ApplicationCall>.(Unit)) {
for (route in routes) {
get(route, call)
}
}
And finally call it like:
routing {
get("/path1", "/path2") { /* your handling method */}
}
Upvotes: 1