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-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 未提供任何額外的配置選項。