Skip to content
Server Plugin

XHttpMethodOverride

必要的相依性io.ktor:ktor-server-method-override

程式碼範例 json-kotlinx-method-override

原生伺服器
Ktor 支援 Kotlin/Native,允許您在不需要額外執行環境或虛擬機的情況下執行伺服器。
支援:✅

XHttpMethodOverride 外掛程式賦予了在 X-HTTP-Method-Override 標頭中傳遞 HTTP 動詞的能力。 如果您的伺服器 API 處理多個 HTTP 動詞(GETPUTPOSTDELETE 等),但用戶端由於特定限制僅能使用有限的動詞集(例如 GETPOST),這將會非常有用。 例如,如果用戶端發送一個將 X-Http-Method-Override 標頭設定為 DELETE 的請求,Ktor 將使用 delete 路由處理常式來處理此請求。

新增相依性

若要使用 XHttpMethodOverride,您需要在建置指令碼中包含 ktor-server-method-override 構件:

Kotlin
Groovy
XML

安裝 XHttpMethodOverride

若要將 XHttpMethodOverride 外掛程式安裝到應用程式,請將其傳遞給指定

模組
模組允許您透過分組路由來建構您的應用程式。
中的 install 函式。 下方的程式碼片段展示了如何安裝 XHttpMethodOverride ...

  • ... 在 embeddedServer 函式呼叫內。
  • ... 在明確定義的 module 內,該模組是 Application 類別的擴充函式。
kotlin
kotlin

配置 XHttpMethodOverride

預設情況下,XHttpMethodOverride 會檢查 X-Http-Method-Override 標頭以決定應處理該請求的路由。 您可以使用 headerName 屬性自訂標頭名稱。

範例

下方的 HTTP 請求使用 POST 動詞,並將 X-Http-Method-Override 標頭設定為 DELETE

http
POST http://0.0.0.0:8080/customer/3
X-Http-Method-Override: DELETE

若要使用 delete 路由處理常式處理此類請求,您需要安裝 XHttpMethodOverride

kotlin
package com.example

import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.plugins.methodoverride.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.serialization.*
import kotlinx.serialization.json.*
import io.ktor.server.util.getValue

@Serializable
data class Customer(val id: Int, val firstName: String, val lastName: String)

fun Application.main() {
    val customerStorage = mutableListOf<Customer>()
    customerStorage.addAll(
        arrayOf(
            Customer(1, "Jane", "Smith"),
            Customer(2, "John", "Smith"),
            Customer(3, "Jet", "Brains")
        )
    )

    install(XHttpMethodOverride)
    install(ContentNegotiation) {
        json(Json)
    }
    routing {
        get("/customer/{id}") {
            val id: Int by call.parameters
            val customer: Customer = customerStorage.find { it.id == id }!!
            call.respond(customer)
        }

        delete("/customer/{id}") {
            val id: Int by call.parameters
            customerStorage.removeIf { it.id == id }
            call.respondText("Customer is removed", status = HttpStatusCode.NoContent)
        }
    }
}

您可以在此處找到完整的範例:json-kotlinx-method-override