Package io.ktor.features

Types

AutoHeadResponse

object AutoHeadResponse : 
    ApplicationFeature<ApplicationCallPipeline, Unit, Unit>

A feature that automatically respond to HEAD requests

CORS

class CORS

CORS feature. Please read http://ktor.io/servers/features/cors.html first before using it.

CachingHeaders

class CachingHeaders

Feature that set CachingOptions headers for every response. It invokes optionsProviders for every response and use first non null caching options

CallId

class CallId

Retrieves and generates if necessary a call id. A call id (or correlation id) could be retrieved_ from a call via CallId.Configuration.retrieve function. Multiple retrieve functions could be configured that will be invoked one by one until one of them return non-null value. If no value has been provided by retrievers then a generator could be applied to generate a new call id. Generators could be provided via CallId.Configuration.generate function. Similar to retrieve, multiple generators could be configured so they will be invoked one by one. Usually call id is passed via io.ktor.http.HttpHeaders.XRequestId so one could use CallId.Configuration.retrieveFromHeader function to retrieve call id from a header.

CallLogging

class CallLogging

Logs application lifecycle and call events.

Compression

class Compression

Feature to compress a response based on conditions and ability of client to decompress it

CompressionEncoder

interface CompressionEncoder

Represents a Compression encoder

CompressionEncoderBuilder

class CompressionEncoderBuilder : ConditionsHolderBuilder

Builder for compression encoder configuration

CompressionEncoderConfig

data class CompressionEncoderConfig

Configuration for an encoder

CompressionOptions

data class CompressionOptions

Compression feature configuration

ConditionalHeaders

class ConditionalHeaders

Feature to check modified/match conditional headers and avoid sending contents if it was not changed

ConditionsHolderBuilder

interface ConditionsHolderBuilder

Represents a builder for conditions

ContentConverter

interface ContentConverter

A custom content converted that could be registered in ContentNegotiation feature for any particular content type Could provide bi-directional conversion implementation. One of the most typical examples of content converter is a json content converter that provides both serialization and deserialization

ContentNegotiation

class ContentNegotiation

This feature provides automatic content conversion according to Content-Type and Accept headers

ContentTypeWithQuality

data class ContentTypeWithQuality

Pair of ContentType and quality usually parsed from HttpHeaders.Accept headers.

DataConversion

class DataConversion : ConversionService

Data conversion feature to serialize and deserialize types using converters registry

DefaultHeaders

class DefaultHeaders

Adds standard HTTP headers Date and Server and provides ability to specify other headers that are included in responses.

DeflateEncoder

object DeflateEncoder : CompressionEncoder

Implementation of the deflate encoder

DelegatingConversionService

class DelegatingConversionService : ConversionService

Custom convertor builder

ForwardedHeaderSupport

object ForwardedHeaderSupport : 
    ApplicationFeature<ApplicationCallPipeline, Unit, Unit>

Forwarded header support. See RFC 7239 https://tools.ietf.org/html/rfc7239

GzipEncoder

object GzipEncoder : CompressionEncoder

Implementation of the gzip encoder

HSTS

class HSTS

HSTS feature that appends Strict-Transport-Security HTTP header to every response. See http://ktor.io/servers/features/hsts.html for details See RFC 6797 https://tools.ietf.org/html/rfc6797

HttpsRedirect

class HttpsRedirect

Redirect non-secure requests to HTTPS

IdentityEncoder

object IdentityEncoder : CompressionEncoder

Implementation of the identity encoder

MutableOriginConnectionPoint

class MutableOriginConnectionPoint : RequestConnectionPoint

Represents a RequestConnectionPoint. Every it’s component is mutable so application features could provide them

PartialContent

class PartialContent

Feature to support requests to specific content ranges.

StatusPages

class StatusPages

Status pages feature that handles exceptions and status codes. Useful to configure default error pages.

XForwardedHeaderSupport

object XForwardedHeaderSupport : 
    ApplicationFeature<ApplicationCallPipeline, Config, Config>

X-Forwarded-* headers support See http://ktor.io/servers/features/forward-headers.html for details

Exceptions

BadRequestException

open class BadRequestException : Exception

Base exception to indicate that the request is not correct due to wrong/missing request parameters, body content or header values. Throwing this exception in a handler will lead to 400 Bad Request response unless a custom io.ktor.features.StatusPages handler registered.

ContentTransformationException

abstract class ContentTransformationException : Exception

Thrown when content cannot be transformed to the desired type. It is not defined which status code will be replied when an exception of this type is thrown and not caught. Depending on child type it could be 4xx or 5xx status code. By default it will be 500 Internal Server Error.

MissingRequestParameterException

class MissingRequestParameterException : BadRequestException

This exception is thrown when a required parameter with name parameterName is missing

NotFoundException

class NotFoundException : Exception

This exception means that the requested resource is not found. HTTP status 404 Not found will be replied when this exception is thrown and not caught. 404 status page could be configured by registering a custom io.ktor.features.StatusPages handler.

ParameterConversionException

class ParameterConversionException : BadRequestException

This exception is thrown when a required parameter with name parameterName couldn’t be converted to the type

RejectedCallIdException

class RejectedCallIdException : IllegalArgumentException

An exception that could be thrown to reject a call due to illegal call id

UnsupportedMediaTypeException

class UnsupportedMediaTypeException : 
    ContentTransformationException

Thrown when there is no conversion for a content type configured. HTTP status 415 Unsupported Media Type will be replied when this exception is thrown and not caught.

Type Aliases

AcceptHeaderContributor

typealias AcceptHeaderContributor = (call: ApplicationCall, acceptedContentTypes: List<ContentTypeWithQuality>) -> List<ContentTypeWithQuality>

Functional type for accepted content types contributor

CallIdProvider

typealias CallIdProvider = (call: ApplicationCall) -> String?

A function that retrieves or generates call id using provided call

CallIdVerifier

typealias CallIdVerifier = (String) -> Boolean

A function that verifies retrieved or generated call id. Should return true for a valid call id. Also it could throw a RejectedCallIdException to reject an ApplicationCall otherwise an illegal call id will be ignored or replaced with generated one.

Extensions for External Classes

kotlin.collections.List

kotlinx.coroutines.CoroutineScope

Properties

CALL_ID_DEFAULT_DICTIONARY

const val CALL_ID_DEFAULT_DICTIONARY: String

The default call id’s generator dictionary

MutableOriginConnectionPointKey

val MutableOriginConnectionPointKey: AttributeKey<MutableOriginConnectionPoint>

A key to install a mutable RequestConnectionPoint

callId

val ApplicationCall.callId: String?

A call id that is retrieved or generated by CallId feature or null (this is possible if there is no call id provided and no generators configured or CallId feature is not installed)

conversionService

Lookup for a conversion service. Returns the default one if the feature wasn’t installed

defaultVersions

val OutgoingContent.defaultVersions: List<Version>

Retrieves LastModified and ETag versions from this OutgoingContent headers

origin

Represents request and connection parameters possibly overridden via https headers. By default it fallbacks to ApplicationRequest.local

Functions

callIdMdc

fun Configuration.callIdMdc(name: String = "CallId"): Unit

Put call id into MDC (diagnostic context value) with name

condition

fun ConditionsHolderBuilder.condition(
    predicate: ApplicationCall.(OutgoingContent) -> Boolean
): Unit

Appends a custom condition to the encoder or Compression configuration. A predicate returns true when a response need to be compressed. If at least one condition is not met then the response compression is skipped.

deflate

fun Configuration.deflate(
    block: CompressionEncoderBuilder.() -> Unit = {}
): Unit

Appends deflate encoder with default priority of 0.9

excludeContentType

fun ConditionsHolderBuilder.excludeContentType(
    vararg mimeTypes: ContentType
): Unit

Appends a content type exclusion condition to the encoder or Compression configuration

generate

fun Configuration.generate(
    length: Int = 64,
    dictionary: String = CALL_ID_DEFAULT_DICTIONARY
): Unit

Generates fixed length call ids using the specified dictionary. Please note that this function generates pseudo-random identifiers via regular java.util.Random and should not be considered as cryptographically secure. Also note that you should use the same dictionary for CallIdVerifier otherwise a generated call id could be discarded or may lead to complete call rejection.

gzip

fun Configuration.gzip(
    block: CompressionEncoderBuilder.() -> Unit = {}
): Unit

Appends gzip encoder

identity

fun Configuration.identity(
    block: CompressionEncoderBuilder.() -> Unit = {}
): Unit

Appends identity encoder

matchContentType

fun ConditionsHolderBuilder.matchContentType(
    vararg mimeTypes: ContentType
): Unit

Appends a content type condition to the encoder or Compression configuration

minimumSize

fun ConditionsHolderBuilder.minimumSize(minSize: Long): Unit

Appends a minimum size condition to the encoder or Compression configuration

parseVersions

fun Headers.parseVersions(): List<Version>

Retrieves LastModified and ETag versions from headers.

statusFile

fun Configuration.statusFile(
    vararg code: HttpStatusCode,
    filePattern: String
): Unit

Register a status page file(s) using filePattern for multiple status code list

suitableCharset

fun ApplicationCall.suitableCharset(
    defaultCharset: Charset = Charsets.UTF_8
): Charset

Detect suitable charset for an application call by Accept header or fallback to defaultCharset

toLogString

fun ApplicationRequest.toLogString(): String

Generates a string representing this ApplicationRequest suitable for logging

withETag

suspend fun ApplicationCall.withETag(
    etag: String,
    putHeader: Boolean = true,
    block: suspend () -> Unit
): Unit

Checks current etag value and pass it through conditions supplied by the remote client. Depends on conditions it produces 410 Precondition Failed or 304 Not modified responses when necessary. Otherwise sets ETag header and delegates to the block function