【问题标题】:How to use multiples routes for same resources如何为相同的资源使用多个路由
【发布时间】:2021-04-21 10:34:46
【问题描述】:

我在 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))
    }
    
    ...
    
}

【问题讨论】:

    标签: kotlin ktor


    【解决方案1】:

    我知道的唯一压缩方法是创建一个包含主路径的全局变量,然后是 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 */}
    }
    

    【讨论】:

    • 这么简单,我想我怎么没想到!谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-18
    • 2013-11-04
    • 2014-04-08
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多