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 不提供任何額外的設定選項。