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
implementation(ktorLibs.server.autoHeadResponse) 上述代码段使用 Ktor 版本目录 (version catalog) 来指定 Ktor 依赖项。
groovy
implementation ktorLibs.server.autoHeadResponse 上述代码段使用 Ktor 版本目录 (version catalog) 来指定 Ktor 依赖项。
xml
<dependency>
<groupId>io.ktor</groupId>
<artifactId>ktor-server-auto-head-response-jvm</artifactId>
<version>${ktor_version}</version>
</dependency>用法
为了使用此功能性,我们需要在应用程序中安装 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 未提供任何额外的配置选项。
