Server Plugin
AutoHeadResponse
必需的依赖项: io.ktor:ktor-server-auto-head-response
代码示例: autohead
原生服务器 支持: ✅ Ktor supports Kotlin/Native and allows you to run a server without an additional runtime or virtual machine.
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 不提供任何额外的配置选项。
