如何为相同的资源使用多个路由
How to use multiples routes for same resources
我在 Ktor 中有很多相同资源的 URI。为了避免重复太多行,我找到了这个解决方案:
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))
}
有没有像这样更优雅的解决方案:
routing {
get("/", "/index", "/home") {
val parameters = ...
call.respond(ThymeleafContent("/index.html", parameters))
}
...
}
我知道的唯一压缩方法是创建一个包含主路径的全局变量,然后 forEach
它。
val homePaths = arrayOf("/path1", "/path2", ...)
...
routing {
homePaths.forEach { path -> get(path, home()) }
}
一个很棒的功能是能够将正则表达式指定为路由方法的输入。
你可以自己做饭的东西是做这种事的 KTX。
fun Routing.get(varargs routes: String, call: suspend PipelineContext<Unit, ApplicationCall>.(Unit)) {
for (route in routes) {
get(route, call)
}
}
最后这样称呼它:
routing {
get("/path1", "/path2") { /* your handling method */}
}
我在 Ktor 中有很多相同资源的 URI。为了避免重复太多行,我找到了这个解决方案:
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))
}
有没有像这样更优雅的解决方案:
routing {
get("/", "/index", "/home") {
val parameters = ...
call.respond(ThymeleafContent("/index.html", parameters))
}
...
}
我知道的唯一压缩方法是创建一个包含主路径的全局变量,然后 forEach
它。
val homePaths = arrayOf("/path1", "/path2", ...)
...
routing {
homePaths.forEach { path -> get(path, home()) }
}
一个很棒的功能是能够将正则表达式指定为路由方法的输入。
你可以自己做饭的东西是做这种事的 KTX。
fun Routing.get(varargs routes: String, call: suspend PipelineContext<Unit, ApplicationCall>.(Unit)) {
for (route in routes) {
get(route, call)
}
}
最后这样称呼它:
routing {
get("/path1", "/path2") { /* your handling method */}
}