XHttpMethodOverride
所需依赖项: io.ktor:ktor-server-method-override
代码示例: json-kotlinx-method-override
XHttpMethodOverride 插件使得能够将 HTTP 动词通过 X-HTTP-Method-Override
header 进行隧道化。 如果您的服务器 API 处理多个 HTTP 动词(例如 GET
、PUT
、POST
、DELETE
等),但客户端由于特定限制只能使用有限的动词集合(例如 GET
和 POST
),这可能会很有用。 例如,如果客户端发送一个 X-Http-Method-Override
header 设置为 DELETE
的请求,Ktor 将使用 delete
路由处理器 来处理此请求。
添加依赖项
要使用 XHttpMethodOverride
,您需要在构建脚本中包含 ktor-server-method-override
artifact:
安装 XHttpMethodOverride
要将 XHttpMethodOverride
插件安装到应用程序中,请将其传递给指定
install
函数。下面的代码片段展示了如何安装 XHttpMethodOverride
... - ... 在
embeddedServer
函数调用内部。 - ... 在显式定义的
module
内部,这是一个Application
类的扩展函数。
配置 XHttpMethodOverride
默认情况下,XHttpMethodOverride
检测 X-Http-Method-Override
header 以确定应处理请求的路由。 您可以使用 headerName
属性来自定义 header 名称。
示例
下面的 HTTP 请求使用 POST
动词,其中 X-Http-Method-Override
header 设置为 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。