Controlling cache headers

预计阅读时间:2分钟

CachingOptions功能增加了发送标头Cache-ControlExpires的功能,这些标头由客户端和代理使用,以一种简单的方式缓存请求.

此功能在io.ktor.features.CachingHeaders类中io.ktor.features.CachingHeaders ,不需要其他工件.

与许多其他功能一样,已安装了基本功能,但是要执行此操作,您必须使用以下方法定义options块,将outputContent转换为CachingOptions:

install(CachingHeaders) {
    options { outgoingContent ->
        when (outgoingContent.contentType?.withoutParameters()) {
            ContentType.Text.CSS -> CachingOptions(CacheControl.MaxAge(maxAgeSeconds = 24 * 60 * 60))
            else -> null
        }
    }
}

选项配置方法使您可以定义代码,以从提供的CachingOptions outgoingContent: OutgoingContent有选择地选择CachingOptions . 例如,您可以使用传出消息的Content-Type来确定要使用哪个Cache-Control.

CachingOptions and CacheControl

options高阶函数要求您返回描述CacheControlCachingOption以及可选的到期时间:

data class CachingOptions(val cacheControl: CacheControl? = null, val expires: ZonedDateTime? = null)

sealed class CacheControl(val visibility: Visibility?) {
    enum class Visibility { Public, Private }
    
    class NoCache(visibility: Visibility?) : CacheControl(visibility)
    class NoStore(visibility: Visibility?) : CacheControl(visibility)
    class MaxAge(val maxAgeSeconds: Int, val proxyMaxAgeSeconds: Int? = null, val mustRevalidate: Boolean = false, val proxyRevalidate: Boolean = false, visibility: Visibility? = null) : CacheControl(visibility)
}

如果您有多个选项,则每个匹配选项都会附加多个Cache-Control标头.

by  ICOPY.SITE