Creating Custom Features

note

Creating Custom Features - 图1

This help topic is in development and will be updated in the future.

You can develop your own features and reuse them across all your Ktor applications, or you can share them with the community. A typical feature has the following structure:

  1. class CustomFeature(configuration: Configuration) {
  2. val prop = configuration.prop // Copies a snapshot of the mutable config into an immutable property.
  3. class Configuration {
  4. var prop = "value" // Mutable property.
  5. }
  6. // Implements ApplicationFeature as a companion object.
  7. companion object Feature : ApplicationFeature<ApplicationCallPipeline, CustomFeature.Configuration, CustomFeature> {
  8. // Creates a unique key for the feature.
  9. override val key = AttributeKey<CustomFeature>("CustomFeature")
  10. // Code to execute when installing the feature.
  11. override fun install(pipeline: ApplicationCallPipeline, configure: Configuration.() -> Unit): CustomFeature {
  12. // It is responsibility of the install code to call the `configure` method with the mutable configuration.
  13. val configuration = CustomFeature.Configuration().apply(configure)
  14. // Create the feature, providing the mutable configuration so the feature reads it keeping an immutable copy of the properties.
  15. val feature = CustomFeature(configuration)
  16. // Intercept a pipeline.
  17. pipeline.intercept(…) {
  18. // Perform things in that interception point.
  19. }
  20. return feature
  21. }
  22. }
  23. }

CustomFeature is a feature instance class, which should be immutable to avoid unintended side-effects in a highly concurrent environment. Feature implementation should be thread-safe as it will be called from multiple threads.

The Configuration instance is handed to the user installation script, allowing feature configuration usually containing mutable properties and configuration methods.

The Feature companion object conforms the ApplicationFeature interface and acts as a glue to construct the actual CustomFeature with the right Configuration.

A custom feature can be installed normally with the standard install function:

  1. fun Application.main() {
  2. install(CustomFeature) { // Install a custom feature
  3. prop = "Hello" // configuration script
  4. }
  5. }

See a complete example in the custom feature sample.