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

标签 kotlin routing 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}
   }
}

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

最佳答案

抱歉迟到了。在我的代码中,我制作了路线,有些路线有一个拦截器来测量和记录执行时间,而其他路线则没有。因此,我按照文档中的示例( 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()
        }
    }
}

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

希望对这么晚的事件有所帮助。

关于kotlin - 如何在 ktor 中创建可重用的拦截器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55747196/

相关文章:

android - 如何解析 Kotlin 中 Room 库的注解?

android - 类型推断失败 Kotlin rxjava 映射使用

ruby-on-rails - 如何在 Rails 4 中将一组资源路由别名或重写到另一个命名空间?

kotlin - 使用 Ktor Kotlin 处理 FreeMaker 模板

kotlin - Kotlin的SequenceBuilder的线程安全性

reactjs - 什么是识别我当前使用 react-router 4 的路线的更好方法

CodeIgniter URL 路由 - SEO 友好的 URL

android - 将 Ktor 添加到 Kotlin Multiplatform Mobile 导致未解析的引用 : HttpClient

google-app-engine - 部署到 AppEngine 时未调用 Ktor 应用程序的 Main 方法

android - Android 中的库模块不包含依赖项