Skip to content
Server Plugin

XHttpMethodOverride

必需的依赖项io.ktor:ktor-server-method-override

代码示例 json-kotlinx-method-override

Native 服务器
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