Skip to content
Server Plugin

AutoHeadResponse

必要相依性io.ktor:ktor-server-auto-head-response

程式碼範例 autohead

Native 伺服器
Ktor 支援 Kotlin/Native,允許您在沒有額外執行階段或虛擬機的情況下執行伺服器。
支援:✅

AutoHeadResponse 外掛程式讓我們能夠自動回應每個已定義 GET 的路由之 HEAD 請求。如果您需要在獲取實際內容之前在用戶端以某種方式處理回應,可以使用 AutoHeadResponse 來避免建立單獨的 head 處理常式。例如,呼叫 respondFile 函式會自動在回應中加入 Content-LengthContent-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 不提供任何額外的配置選項。