Creating Custom Feature


您可以开发自己的功能,并在所有Ktor应用程序中重复使用它们,或者可以与社区共享它们. 典型功能具有以下结构:

class CustomFeature(configuration: Configuration) {
    val prop = configuration.prop // Copies a snapshot of the mutable config into an immutable property.
    class Configuration {
       var prop = "value" // Mutable property.

    // Implements ApplicationFeature as a companion object.
    companion object Feature : ApplicationFeature<ApplicationCallPipeline, CustomFeature.Configuration, CustomFeature> {
       // Creates a unique key for the feature.
       override val key = AttributeKey<CustomFeature>("CustomFeature")
       // Code to execute when installing the feature.
       override fun install(pipeline: ApplicationCallPipeline, configure: Configuration.() -> Unit): CustomFeature {
           // It is responsibility of the install code to call the `configure` method with the mutable configuration.
           val configuration = CustomFeature.Configuration().apply(configure)
           // Create the feature, providing the mutable configuration so the feature reads it keeping an immutable copy of the properties. 
           val feature = CustomFeature(configuration)
           // Intercept a pipeline.
           pipeline.intercept() { 
                // Perform things in that interception point.
           return feature

CustomFeature是一个要素实例类,应保持不变,以避免在高度并发的环境中产生意外的副作用. 功能实现应该是线程安全的,因为它将从多个线程中调用.


Feature随行对象符合ApplicationFeature接口,并充当胶水来构建具有正确Configuration的实际CustomFeature .


fun Application.main() {
    install(CustomFeature) { // Install a custom feature
        prop = "Hello" // configuration script

请参阅自定义功能示例中的完整示例 .