对于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))
}
...
}
我知道压缩的唯一方法是先创建一个包含home-paths的全局变量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 */}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句