Package io.ktor.features

Types

Link copied to clipboard
typealias AcceptHeaderContributor = (call: ApplicationCall, acceptedContentTypes: List<ContentTypeWithQuality>) -> List<ContentTypeWithQuality>

Functional type for accepted content types contributor

Link copied to clipboard
object AutoHeadResponse : ApplicationFeature<ApplicationCallPipeline, Unit, Unit>

A feature that automatically respond to HEAD requests

Link copied to clipboard
open class BadRequestException(message: String, cause: Throwable?) : 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.

Link copied to clipboard
sealed class CachedTransformationResult<T : Any>

Represents a cached transformation result from a previous ApplicationCall.receive invocation.

Link copied to clipboard
class CachingHeaders(optionsProviders: List<(OutgoingContent) -> CachingOptions?>)

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

Link copied to clipboard
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.

Link copied to clipboard
typealias CallIdProvider = (call: ApplicationCall) -> String?

A function that retrieves or generates call id using provided call

Link copied to clipboard
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.

Link copied to clipboard
class CallLogging

Logs application lifecycle and call events.

Link copied to clipboard
class Compression(compression: Compression.Configuration)

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

Link copied to clipboard
interface CompressionEncoder

Represents a Compression encoder

Link copied to clipboard
class CompressionEncoderBuilder : ConditionsHolderBuilder

Builder for compression encoder configuration

Link copied to clipboard
data class CompressionEncoderConfig(name: String, encoder: CompressionEncoder, conditions: List<ApplicationCall.(OutgoingContent) -> Boolean>, priority: Double)

Configuration for an encoder

Link copied to clipboard
data class CompressionOptions(encoders: Map<String, CompressionEncoderConfig>, conditions: List<ApplicationCall.(OutgoingContent) -> Boolean>)

Compression feature configuration

Link copied to clipboard
class ConditionalHeaders(versionProviders: List<suspend (OutgoingContent) -> List<Version>>)

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

Link copied to clipboard
interface ConditionsHolderBuilder

Represents a builder for conditions

Link copied to clipboard
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

Link copied to clipboard
class ContentNegotiation

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

Link copied to clipboard
abstract class ContentTransformationException(message: String) : 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.

Link copied to clipboard
data class ContentTypeWithQuality(contentType: ContentType, quality: Double)

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

Link copied to clipboard
class CORS(configuration: CORS.Configuration)

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

Link copied to clipboard
class DataConversion(converters: Map<Type, ConversionService>) : ConversionService

Data conversion feature to serialize and deserialize types using converters registry

Link copied to clipboard
class DefaultHeaders(config: DefaultHeaders.Configuration)

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

Link copied to clipboard
object DeflateEncoder : CompressionEncoder

Implementation of the deflate encoder

Link copied to clipboard
class DelegatingConversionService : ConversionService

Custom convertor builder

Link copied to clipboard
class DoubleReceive

This feature provides ability to invoke ApplicationCall.receive several times. Please note that not every type could be received twice. For example, even with this feature installed you can't receive a channel twice (unless Configuration.receiveEntireContent is enabled). Types that always can be received twice or more: ByteArray, String and Parameters. Also some of content transformation features (such as ContentNegotiation) could support it as well. If not specified, a transformation result is not considered as reusable. So a transformation feature may mark a result as reusable by proceeding with a ApplicationReceiveRequest instance having ApplicationReceiveRequest.reusableValue= true. So installing DoubleReceive with ContentNegotiation provides ability to receive a user type that will be deserialized at first receive and then the same instance will be returned for every further receive invocation. When the same receive type requested as the firstly received, the receive pipeline and content transformation are not triggered (except when Configuration.receiveEntireContent = true).

Link copied to clipboard

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

Link copied to clipboard
object GzipEncoder : CompressionEncoder

Implementation of the gzip encoder

Link copied to clipboard
class HSTS(config: HSTS.Configuration)

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

Link copied to clipboard
class HttpsRedirect(config: HttpsRedirect.Configuration)

Redirect non-secure requests to HTTPS

Link copied to clipboard
object IdentityEncoder : CompressionEncoder

Implementation of the identity encoder

Link copied to clipboard
class MissingRequestParameterException(parameterName: String) : BadRequestException, CopyableThrowable<MissingRequestParameterException>

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

Link copied to clipboard
class MutableOriginConnectionPoint constructor(delegate: RequestConnectionPoint) : RequestConnectionPoint

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

Link copied to clipboard
class NotFoundException(message: String?) : 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.

Link copied to clipboard
class ParameterConversionException(parameterName: String, type: String, cause: Throwable?) : BadRequestException, CopyableThrowable<ParameterConversionException>

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

Link copied to clipboard
class PartialContent(maxRangeCount: Int)

Feature to support requests to specific content ranges.

Link copied to clipboard
class RejectedCallIdException(illegalCallId: String) : IllegalArgumentException, CopyableThrowable<RejectedCallIdException>

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

Link copied to clipboard
class RequestReceiveAlreadyFailedException : Exception

Thrown when a request receive was failed during the previous ApplicationCall.receive invocation so this receive attempt is simply replaying the previous exception cause.

Link copied to clipboard
class StatusPages(config: StatusPages.Configuration)

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

Link copied to clipboard
class UnsupportedMediaTypeException(contentType: ContentType) : ContentTransformationException, CopyableThrowable<UnsupportedMediaTypeException>

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.

Link copied to clipboard

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

Functions

Link copied to clipboard
fun CallLogging.Configuration.callIdMdc(name: String = "CallId")

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

Link copied to clipboard
fun ConditionsHolderBuilder.condition(predicate: ApplicationCall.(OutgoingContent) -> Boolean)

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.

Link copied to clipboard
fun Compression.Configuration.deflate(block: CompressionEncoderBuilder.() -> Unit = {})

Appends deflate encoder with default priority of 0.9

Link copied to clipboard
fun ConditionsHolderBuilder.excludeContentType(vararg mimeTypes: ContentType)

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

Link copied to clipboard
fun CallId.Configuration.generate(length: Int = 64, dictionary: String = CALL_ID_DEFAULT_DICTIONARY)

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.

Link copied to clipboard
fun Compression.Configuration.gzip(block: CompressionEncoderBuilder.() -> Unit = {})

Appends gzip encoder

Link copied to clipboard
fun Compression.Configuration.identity(block: CompressionEncoderBuilder.() -> Unit = {})

Appends identity encoder

Link copied to clipboard
fun ConditionsHolderBuilder.matchContentType(vararg mimeTypes: ContentType)

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

Link copied to clipboard
fun ConditionsHolderBuilder.minimumSize(minSize: Long)

Appends a minimum size condition to the encoder or Compression configuration.

Link copied to clipboard
fun Headers.parseVersions(): List<Version>

Retrieves LastModified and ETag versions from headers.

Link copied to clipboard

Returns a list of content types sorted by quality, number of asterisks and number of parameters.

Link copied to clipboard
fun StatusPages.Configuration.statusFile(vararg code: HttpStatusCode, filePattern: String)

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

Link copied to clipboard
fun ApplicationCall.suitableCharset(defaultCharset: Charset = Charsets.UTF_8): Charset

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

Link copied to clipboard
fun ApplicationRequest.toLogString(): String

Generates a string representing this ApplicationRequest suitable for logging

Link copied to clipboard
suspend fun ApplicationCall.withETag(etag: String, putHeader: Boolean = true, block: suspend () -> 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

Link copied to clipboard
fun CoroutineScope.writeMultipleRanges(channelProducer: (LongRange) -> ByteReadChannel, ranges: List<LongRange>, fullLength: Long?, boundary: String, contentType: String): ByteReadChannel

Start multirange response writer coroutine

Properties

Link copied to clipboard
const val CALL_ID_DEFAULT_DICTIONARY: String

The default call id's generator dictionary

Link copied to clipboard
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)

Link copied to clipboard

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

Link copied to clipboard
val OutgoingContent.defaultVersions: List<Version>

Retrieves LastModified and ETag versions from this OutgoingContent headers

Link copied to clipboard
var CORS.Configuration.maxAge: Duration
Link copied to clipboard
var HSTS.Configuration.maxAge: Duration
Link copied to clipboard
var CookieConfiguration.maxAge: Duration?

Cookie time to live duration or null for session cookies. Session cookies are client-driven. For example, a web browser usually removes session cookies at browser or window close unless the session is restored.

Link copied to clipboard

Duration to tell the client to keep CORS options.

Link copied to clipboard
Link copied to clipboard

A key to install a mutable RequestConnectionPoint

Link copied to clipboard
val ApplicationRequest.origin: RequestConnectionPoint

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