如何在 ktor 中创建可重用的拦截器?

Cam*_*ima 4 routing kotlin ktor

在 ktor 中,进行自定义权限检查的方法似乎是通过拦截器,如下所示:

route("/portal") {
   route("articles") { … }
   route("admin") {


    intercept(ApplicationCallPipeline.Features) { … } // verify admin privileges
      route("article/{id}") { … } // manage article with {id}
      route("profile/{id}") { … } // manage profile with {id}
   }
}
Run Code Online (Sandbox Code Playgroud)

提取拦截器逻辑以供代码库中其他地方的其他路由重用的最佳方法是什么?

Her*_*hon 6

抱歉迟到了。在我的代码中,我制作了路线,有些路线有一个拦截器来测量和记录执行时间,而其他路线则没有。所以我按照文档中的例子做了一个函数(https://ktor.io/advanced/pipeline/route.html#),然后我有但是这个函数围绕着需要测量的路由块.

请在下面找到我的代码

install(Routing) {
    val konfig = HoconKonfigAdapter()
    val contextPath = konfig.get("ktor.deployment.context-path")
    route("$contextPath/api/v1") {
        val registry = feature(Metrics).registry

        healthEndPoints()
        metricsEndPoints(registry)
        routeWithMeasureTime {
            catalogSiEndPoints()
            reunionCatalogEditoEndPoints()
            telesurveillanceCatalogEditoEndPoints()
            catalogLegacyEndPoints()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

将拦截和测量块 routeWithMeasureTime 内的所有路线。另一个,没有。

希望对这么晚的活动有所帮助。