Skip to content

自訂外掛程式 - Base API ​

程式碼範例: custom-plugin-base-api

Ktor 提供了用於開發自訂外掛程式的 Base API,以在多個應用程式之間實作可重複使用的功能性。

Base API 讓您可以攔截不同的管線階段,並為請求與回應處理加入自訂邏輯。例如,您可以攔截 Monitoring 階段來記錄傳入請求或收集指標。

建立外掛程式 ​

若要使用 Base API 建立自訂外掛程式:

  1. 建立外掛程式類別並宣告實作外掛程式介面的伴生物件。
  2. 在伴生物件中實作 key 屬性與 install() 函式。
  3. 提供外掛程式配置。
  4. 透過攔截所需的管線階段來處理呼叫。
  5. 安裝外掛程式。

建立伴生物件 ​

自訂外掛程式的類別必須具有實作下列介面之一的伴生物件:

BaseApplicationPlugin 介面接受下列型別參數:

  • 外掛程式支援的管線型別。
  • 外掛程式的配置型別。
  • 外掛程式執行個體型別。
kotlin
class CustomHeader() {
    companion object Plugin : BaseApplicationPlugin<ApplicationCallPipeline, Configuration, CustomHeader> {
        // ...
    }
}

實作 'key' 屬性與 'install()' 函式 ​

實作 BaseApplicationPlugin 的伴生物件必須定義以下內容:

  • key 屬性用於識別外掛程式。Ktor 將外掛程式執行個體儲存在應用程式的屬性中,並使用此索引鍵存取該外掛程式執行個體。
  • install() 函式用於配置外掛程式。在此函式中,攔截所需的管線階段並傳回外掛程式執行個體。處理呼叫章節介紹了如何攔截管線階段。
kotlin
class CustomHeader() {
    companion object Plugin : BaseApplicationPlugin<ApplicationCallPipeline, Configuration, CustomHeader> {
        override val key = AttributeKey<CustomHeader>("CustomHeader")
        override fun install(pipeline: ApplicationCallPipeline, configure: Configuration.() -> Unit): CustomHeader {
            val plugin = CustomHeader()
            // Intercept a pipeline ...
            return plugin
        }
    }
}

處理呼叫 ​

在自訂外掛程式中,您可以透過攔截現有管線階段或新定義的階段來處理請求與回應。例如,驗證 (Authentication) 外掛程式將 Authenticate 和 Challenge 自訂階段新增至預設管線中。

攔截特定階段可讓您存取呼叫處理的特定階段:

  • ApplicationCallPipeline.Monitoring:使用此階段進行請求記錄、指標、執行緒以及類似的監控任務。
  • ApplicationCallPipeline.Plugins:使用此階段處理呼叫或修改回應參數,例如附加自訂標頭。
  • ApplicationReceivePipeline.Transform 與 ApplicationSendPipeline.Transform:使用這些階段存取並轉換從用戶端接收或傳送至用戶端的資料。

以下範例攔截 ApplicationCallPipeline.Plugins 階段並將自訂標頭附加到每個回應:

kotlin
class CustomHeader() {
    companion object Plugin : BaseApplicationPlugin<ApplicationCallPipeline, Configuration, CustomHeader> {
        override val key = AttributeKey<CustomHeader>("CustomHeader")
        override fun install(pipeline: ApplicationCallPipeline, configure: Configuration.() -> Unit): CustomHeader {
            val plugin = CustomHeader()
            pipeline.intercept(ApplicationCallPipeline.Plugins) {
                call.response.header("X-Custom-Header", "Hello, world!")
            }
            return plugin
        }
    }
}

在此範例中,標頭名稱和值是寫死的。若要讓外掛程式可重複使用,請提供配置,允許使用者指定標頭名稱和值。

自訂外掛程式可以在不同的處理常式之間共享與呼叫相關聯的值。若要了解更多,請參閱 共享呼叫狀態。

提供外掛程式配置 ​

上一節示範了如何建立一個將預先定義的自訂標頭附加至每個回應的外掛程式。若要讓此外掛程式可重複使用,請定義允許使用者指定標頭名稱和值的配置。

首先,在外掛程式類別內定義一個配置類別:

kotlin
class Configuration {
    var headerName = "Custom-Header-Name"
    var headerValue = "Default value"
}

您可以在外掛程式安裝期間更新外掛程式配置屬性。如果外掛程式在攔截器中使用這些值,請將它們儲存在 install() 函式內的區域變數中:

kotlin
class CustomHeader(configuration: Configuration) {
    private val name = configuration.headerName
    private val value = configuration.headerValue

    class Configuration {
        var headerName = "Custom-Header-Name"
        var headerValue = "Default value"
    }
}

接著,在 install() 函式中讀取配置並使用其屬性:

kotlin
class CustomHeader(configuration: Configuration) {
    private val name = configuration.headerName
    private val value = configuration.headerValue

    class Configuration {
        var headerName = "Custom-Header-Name"
        var headerValue = "Default value"
    }

    companion object Plugin : BaseApplicationPlugin<ApplicationCallPipeline, Configuration, CustomHeader> {
        override val key = AttributeKey<CustomHeader>("CustomHeader")
        override fun install(pipeline: ApplicationCallPipeline, configure: Configuration.() -> Unit): CustomHeader {
            val configuration = Configuration().apply(configure)
            val plugin = CustomHeader(configuration)
            pipeline.intercept(ApplicationCallPipeline.Plugins) {
                call.response.header(plugin.name, plugin.value)
            }
            return plugin
        }
    }
}

安裝外掛程式 ​

若要將自訂外掛程式安裝至您的應用程式,請呼叫 Application.install() 函式並傳遞所需的配置參數:

kotlin
install(CustomHeader) {
    headerName = "X-Custom-Header"
    headerValue = "Hello, world!"
}

範例 ​

下列範例示範使用 Base API 建置的數個自訂外掛程式。

如需完整的可執行專案,請參閱 custom-plugin-base-api。

請求記錄 ​

下列範例建立一個記錄傳入請求的自訂外掛程式:

kotlin
package com.example.plugins

import io.ktor.serialization.*
import io.ktor.server.application.*
import io.ktor.server.plugins.*
import io.ktor.util.*

class RequestLogging {
    companion object Plugin : BaseApplicationPlugin<ApplicationCallPipeline, Configuration, RequestLogging> {
        override val key = AttributeKey<RequestLogging>("RequestLogging")
        override fun install(pipeline: ApplicationCallPipeline, configure: Configuration.() -> Unit): RequestLogging {
            val plugin = RequestLogging()
            pipeline.intercept(ApplicationCallPipeline.Monitoring) {
                call.request.origin.apply {
                    println("Request URL: $scheme://$localHost:$localPort$uri")
                }
            }
            return plugin
        }
    }
}

自訂標頭 ​

下列範例建立一個將自訂標頭附加至每個回應的外掛程式:

kotlin
package com.example.plugins

import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.util.*

class CustomHeader(configuration: Configuration) {
    private val name = configuration.headerName
    private val value = configuration.headerValue

    class Configuration {
        var headerName = "Custom-Header-Name"
        var headerValue = "Default value"
    }

    companion object Plugin : BaseApplicationPlugin<ApplicationCallPipeline, Configuration, CustomHeader> {
        override val key = AttributeKey<CustomHeader>("CustomHeader")
        override fun install(pipeline: ApplicationCallPipeline, configure: Configuration.() -> Unit): CustomHeader {
            val configuration = Configuration().apply(configure)
            val plugin = CustomHeader(configuration)
            pipeline.intercept(ApplicationCallPipeline.Plugins) {
                call.response.header(plugin.name, plugin.value)
            }
            return plugin
        }
    }
}

主體轉換 ​

下列範例建立一個轉換請求與回應主體的外掛程式:

kotlin
package com.example.plugins

import io.ktor.serialization.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.util.*
import io.ktor.utils.io.*

class DataTransformation {
    companion object Plugin : BaseApplicationPlugin<ApplicationCallPipeline, Configuration, DataTransformation> {
        override val key = AttributeKey<DataTransformation>("DataTransformation")
        override fun install(pipeline: ApplicationCallPipeline, configure: Configuration.() -> Unit): DataTransformation {
            val plugin = DataTransformation()
            pipeline.receivePipeline.intercept(ApplicationReceivePipeline.Transform) { data ->
                val newValue = (data as ByteReadChannel).readLine()?.toInt()?.plus(1)
                if (newValue != null) {
                    proceedWith(newValue)
                }
            }
            pipeline.sendPipeline.intercept(ApplicationSendPipeline.Transform) { data ->
                if (subject is Int) {
                    val newValue = data.toString().toInt() + 1
                    proceedWith(newValue.toString())
                }
            }
            return plugin
        }
    }
}

管線 ​

Ktor 中的 Pipeline 是按一個或多個有序階段分組的攔截器集合。每個攔截器都可以在請求處理繼續之前和之後執行自訂邏輯。

ApplicationCallPipeline 執行應用程式呼叫。它定義了以下階段:

  • Setup:準備呼叫及其屬性以進行處理。
  • Monitoring:追蹤呼叫。使用此階段進行請求記錄、指標、錯誤處理以及類似任務。
  • Plugins:處理呼叫。大多數外掛程式會攔截此階段。
  • Call:完成呼叫。
  • Fallback:處理未被先前階段處理的呼叫。

管線階段與新 API 處理常式的對應 ​

您可以使用簡化的自訂外掛程式 API 來建立自訂外掛程式。在大多數情況下,此 API 不需要直接了解 Ktor 內部概念(例如管線和階段)。 相反地,它為請求與回應處理的不同階段提供了如 onCall()、onCallReceive() 和 onCallRespond() 等處理常式。

下表顯示 Base API 管線階段如何對應到簡化 API 的處理常式:

Base API新 API
before ApplicationCallPipeline.Setupon(CallFailed)
ApplicationCallPipeline.Setupon(CallSetup)
ApplicationCallPipeline.PluginsonCall()
ApplicationCallPipeline.CallonCallValidators()
ApplicationReceivePipeline.TransformonCallReceive()
ApplicationSendPipeline.TransformonCallRespond()
ApplicationSendPipeline.Afteron(ResponseBodyReadyForSend)
ApplicationSendPipeline.Engineon(ResponseSent)
after Authentication.ChallengePhaseon(AuthenticationChecked)