Server Plugin
状态页面
必需依赖项:io.ktor:ktor-server-status-pages
代码示例: status-pages
Native 服务器Ktor 支持 Kotlin/Native,并允许您在无需额外运行时或虚拟机的情况下运行服务器。支持:✅
StatusPages 插件允许 Ktor 应用程序根据抛出的异常或状态码对任何失败状态做出适当响应。
添加依赖项
要使用 StatusPages,请将 ktor-server-status-pages 工件添加到构建脚本中:
kotlin
implementation(ktorLibs.server.statusPages) 上述代码段使用 Ktor 版本目录来指定 Ktor 依赖项。
groovy
implementation ktorLibs.server.statusPages 上述代码段使用 Ktor 版本目录来指定 Ktor 依赖项。
xml
<dependency>
<groupId>io.ktor</groupId>
<artifactId>ktor-server-status-pages-jvm</artifactId>
<version>${ktor_version}</version>
</dependency>安装 StatusPages
要将 StatusPages 插件安装到应用程序中,请将其传递给指定模块模块允许您通过对路由进行分组来构建应用程序结构。中的 install 函数。 以下示例展示了如何安装 StatusPages:
- 在
embeddedServer()函数调用中。 - 在
Application类上显式定义的module()扩展函数中。
kotlin
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.application.*
import io.ktor.server.plugins.statuspages.*
fun main() {
embeddedServer(Netty, port = 8080) {
install(StatusPages)
// ...
}.start(wait = true)
}kotlin
import io.ktor.server.application.*
import io.ktor.server.plugins.statuspages.*
// ...
fun Application.module() {
install(StatusPages)
// ...
}配置 StatusPages
StatusPages 插件提供了三个主要的配置选项:
- exceptions:根据映射的异常类配置响应
- status:针对状态码值配置响应
- statusFile:从类路径配置基于文件的响应
异常
exception 处理程序允许您处理导致 Throwable 异常的调用。在最基础的情况下,可以为任何异常配置 500 HTTP 状态码:
kotlin
install(StatusPages) {
exception<Throwable> { call, cause ->
call.respondText(text = "500: $cause" , status = HttpStatusCode.InternalServerError)
}
}您还可以检查特定异常并返回所需的内容作为响应:
kotlin
install(StatusPages) {
exception<Throwable> { call, cause ->
if(cause is AuthorizationException) {
call.respondText(text = "403: $cause" , status = HttpStatusCode.Forbidden)
} else {
call.respondText(text = "500: $cause" , status = HttpStatusCode.InternalServerError)
}
}
}状态码
status 处理程序提供了根据状态码返回特定内容进行响应的功能。以下示例展示了当服务器上缺少资源(404 状态码)时如何对请求做出响应:
kotlin
install(StatusPages) {
status(HttpStatusCode.NotFound) { call, status ->
call.respondText(text = "404: Page Not Found", status = status)
}
}状态文件
statusFile 处理程序允许您根据状态码提供 HTML 页面响应。假设您的项目在 resources 文件夹中包含 error401.html 和 error402.html 两个 HTML 页面。在这种情况下,您可以像下面这样使用 statusFile 来处理 401 和 402 状态码:
kotlin
install(StatusPages) {
statusFile(HttpStatusCode.Unauthorized, HttpStatusCode.PaymentRequired, filePattern = "error#.html")
}statusFile 处理程序会将已配置状态列表中的任何 # 字符替换为对应的状态码值。
您可以在此处找到完整示例:status-pages。
