Attributes

note

Attributes - 图1

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

Ktor offers an Attributes class that acts as a small typed instance container/dependency injector.

For the server, the ApplicationCall contains an attributes property including an instance of this class (call.attributes). The lifespan of this container is the call: beginning when the request has started and ending when the response has been sent.

You can set as many attributes as required per call on an interceptor and retrieve them later in another interceptor.

In the case of the client, the HttpRequest also contains an attributes property. So from a HttpClientCall instance, you can access the attributes with call.request.attributes.

Basic usage

It is possible to define your own typed attributes by creating instances of the AttributeKey class like this:

  1. // Declared as a global property
  2. val MyAttributeKey = AttributeKey<Int>("MyAttributeKey")

You can later set the attributes with:

  1. attributes.put(MyAttributeKey, 10)

And retrieve them in another interceptor by calling:

  1. attributes.get(MyAttributeKey)

API reference

The full interface for this class looks like:

  1. interface Attributes {
  2. operator fun <T : Any> get(key: AttributeKey<T>): T
  3. fun <T : Any> getOrNull(key: AttributeKey<T>): T?
  4. operator fun contains(key: AttributeKey<*>): Boolean
  5. fun <T : Any> put(key: AttributeKey<T>, value: T)
  6. fun <T : Any> remove(key: AttributeKey<T>)
  7. fun <T : Any> take(key: AttributeKey<T>): T = get(key).also { remove(key) }
  8. fun <T : Any> takeOrNull(key: AttributeKey<T>): T? = getOrNull(key).also { remove(key) }
  9. fun <T : Any> computeIfAbsent(key: AttributeKey<T>, block: () -> T): T
  10. val allKeys: List<AttributeKey<*>>
  11. }