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:從類別路徑 (classpath) 設定檔案回應
例外
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。
