Controlling cache headers

The CachingOptions feature adds the ability to send the headers Cache-Control and Expiresused by clients and proxies to cache requests in an easy way.

This feature is defined in the class io.ktor.features.CachingHeaders and no additional artifacts are required.

The basic feature is installed just like many others, but for it to do something, you have to defineoptions blocks transforming outputContent to CachingOptions using for example:

  1. install(CachingHeaders) {
  2. options { outgoingContent ->
  3. when (outgoingContent.contentType?.withoutParameters()) {
  4. ContentType.Text.CSS -> CachingOptions(CacheControl.MaxAge(maxAgeSeconds = 24 * 60 * 60))
  5. else -> null
  6. }
  7. }
  8. }

The options configuration method, allows you to define code to optionally select a CachingOptionsfrom a provided outgoingContent: OutgoingContent.You can, for example, use the Content-Type of the outgoing message to determine which Cache-Control to use.

CachingOptions and CacheControl

The options high order function requires you to return a CachingOption that describes a CacheControlplus an optional expiring time:

  1. data class CachingOptions(val cacheControl: CacheControl? = null, val expires: ZonedDateTime? = null)
  2. sealed class CacheControl(val visibility: Visibility?) {
  3. enum class Visibility { Public, Private }
  4. class NoCache(visibility: Visibility?) : CacheControl(visibility)
  5. class NoStore(visibility: Visibility?) : CacheControl(visibility)
  6. class MaxAge(val maxAgeSeconds: Int, val proxyMaxAgeSeconds: Int? = null, val mustRevalidate: Boolean = false, val proxyRevalidate: Boolean = false, visibility: Visibility? = null) : CacheControl(visibility)
  7. }

If you have several options, that would append several Cache-Control headers per each matching option.