gpt4 book ai didi

caching - 在Ktor中用缓存头响应图像

转载 作者:行者123 更新时间:2023-12-02 12:46:32 26 4
gpt4 key购买 nike

返回由Ktor提供的静态图像的缓存头的正确方法是什么?

我有以下Ktor设置:

在我的main中:

embeddedServer(
Netty,
watchPaths = listOf("module"),
module = Application::module,
port = if (ENV.env == LOCAL) {
8080
} else {
80
}
).apply {
start(wait = true)
}

然后在主外:
fun Application.module() {
if (ENV.env != LOCAL) {
install(ForwardedHeaderSupport)
install(XForwardedHeaderSupport)
install(HttpsRedirect)
}
install(CachingHeaders) {
options { outgoingContent ->
when (outgoingContent.contentType?.withoutParameters()) {
ContentType.Image.Any -> CachingOptions(CacheControl.MaxAge(maxAgeSeconds = 30 * 24 * 60 * 60))
else -> null
}
}
}
install(Compression) {
gzip {
priority = 1.0
}
deflate {
priority = 10.0
minimumSize(1024) // condition
}
}

routing {
static("/js/") {
resources("/js/")
}

static("/css/") {
resources("/css/")
}

static("/favicons") {
resources("/favicons/")
}

static("/img/") {
resources("/static/img/")
resources("/static/images/")
resources("/background/")
resources("/logos/")
resources("/icons/")
}
}
}

但是这些图像没有缓存头,有什么想法吗?

enter image description here

更新:

ContentType.Image.Any更改为 ContentType.Image.JPEG似乎可行。查看 Image的源代码,它似乎映射到ContentType( image*),但根本不匹配任何图像类型。
install(CachingHeaders) {
options { outgoingContent ->
when (outgoingContent.contentType?.withoutParameters()) {
ContentType.Image.JPEG -> CachingOptions(
cacheControl = CacheControl.MaxAge(
mustRevalidate = false,
maxAgeSeconds = 30 * 24 * 60 * 60,
visibility = CacheControl.Visibility.Public
)
)
else -> null
}
}
}

在此期间提交了一个错误:
https://github.com/ktorio/ktor/issues/1366

最佳答案

事实证明,正在对*而不是实际文件类型进行标准的eqauls检查,因此使用match可以解决该问题:

install(CachingHeaders) {
options { outgoingContent ->
if (outgoingContent.contentType?.withoutParameters()?.match(ContentType.Image.Any) == true) {
CachingOptions(
cacheControl = CacheControl.MaxAge(
mustRevalidate = false,
maxAgeSeconds = 6 * 30 * 24 * 60 * 60,
visibility = CacheControl.Visibility.Public
)
)
} else {
null
}
}
}

关于caching - 在Ktor中用缓存头响应图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57978856/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com