Server Plugin
AutoHeadResponse
所需依赖项: io.ktor:ktor-server-auto-head-response
代码示例: autohead
原生服务器支持: ✅ Ktor 支持 Kotlin/Native,允许你在没有额外运行时或虚拟机的情况下运行服务器。
AutoHeadResponse 插件提供了针对每个定义了 GET
的路由自动响应 HEAD
请求的能力。如果你需要在客户端获取实际内容之前对响应进行某些处理,可以使用 AutoHeadResponse 来避免创建单独的 head 处理程序。例如,调用 respondFile 函数会自动向响应添加 Content-Length
和 Content-Type
标头,你可以在下载文件之前在客户端获取此信息。
添加依赖项
要使用 AutoHeadResponse
,你需要将 ktor-server-auto-head-response
构件添加到构建脚本中:
Kotlin
Groovy
XML
用法
为了利用此功能,我们需要在应用程序中安装 AutoHeadResponse
插件。
kotlin
import io.ktor.server.application.*
import io.ktor.server.plugins.autohead.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
fun Application.main() {
install(AutoHeadResponse)
routing {
get("/home") {
call.respondText("This is a response to a GET, but HEAD also works")
}
}
}
在我们的示例中,/home
路由现在将响应 HEAD
请求,即使没有为此动词显式定义。
需要注意的是,如果我们使用此插件,对于相同的 GET
路由,自定义的 HEAD
定义将被忽略。
选项
AutoHeadResponse 不提供任何额外的配置选项。