XHttpMethodOverride
所需依賴: io.ktor:ktor-server-method-override
程式碼範例: json-kotlinx-method-override
XHttpMethodOverride 外掛程式啟用在 X-HTTP-Method-Override
標頭內部通道 HTTP 動詞的功能。 如果您的伺服器 API 處理多個 HTTP 動詞(如 GET
、PUT
、POST
、DELETE
等),但客戶端由於特定限制只能使用有限的動詞集合(例如 GET
和 POST
),這可能會很有用。 舉例來說,如果客戶端傳送一個請求,其中 X-Http-Method-Override
標頭設定為 DELETE
,Ktor 將使用 delete
路由處理器 來處理此請求。
新增依賴項
要使用 XHttpMethodOverride
,您需要在建置腳本中包含 ktor-server-method-override
artifact:
安裝 XHttpMethodOverride
要將 XHttpMethodOverride
外掛程式安裝到應用程式, 請將其傳遞給指定
install
函數。 下面的程式碼片段顯示了如何安裝 XHttpMethodOverride
... - ... 在
embeddedServer
函數呼叫內部。 - ... 在明確定義的
module
內部,它是一個Application
類別的擴充函數。
配置 XHttpMethodOverride
預設情況下,XHttpMethodOverride
會檢查 X-Http-Method-Override
標頭以確定應處理請求的路由。 您可以使用 headerName
屬性來自訂標頭名稱。
範例
下面的 HTTP 請求使用 POST
動詞,並將 X-Http-Method-Override
標頭設定為 DELETE
:
POST http://0.0.0.0:8080/customer/3
X-Http-Method-Override: DELETE
要使用 delete
路由處理器 處理此類請求,您需要安裝 XHttpMethodOverride
:
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。