【问题标题】:How to create reusable interceptors in ktor?如何在 ktor 中创建可重用的拦截器?
【发布时间】:2019-09-08 20:38:27
【问题描述】:

在 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}
   }
}

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

【问题讨论】:

    标签: kotlin routing ktor


    【解决方案1】:

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

    block routeWithMeasureTime 内的所有路由都会被截取和测量。另一个,没有。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-28
      • 2019-10-20
      • 2021-04-22
      • 2021-11-08
      • 2022-01-13
      • 1970-01-01
      • 2014-09-30
      • 1970-01-01
      相关资源
      最近更新 更多