如何在 Ktor 中列出已配置的路由

How to list configured routes in Ktor

我正在建立一个包含多个模块的项目,其中包含不同版本的 api。

为了验证正确的路由配置,我想将配置的路由打印到应用程序日志,就像在 spring 框架中所做的那样。

这可能吗?我应该使用什么?

您可以通过从根开始一直向下递归遍历路由并仅使用 HTTP 方法选择器过滤路由来实现。此解决方案描述为 here

fun Application.module() {
    // routing configuration goes here

    val root = feature(Routing)
    val allRoutes = allRoutes(root)
    val allRoutesWithMethod = allRoutes.filter { it.selector is HttpMethodRouteSelector }
    allRoutesWithMethod.forEach {
        println("route: $it")
    }
}

fun allRoutes(root: Route): List<Route> {
    return listOf(root) + root.children.flatMap { allRoutes(it) }
}

请注意,以上代码必须放在路由配置之后。