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 동사(verb)를 터널링하는 기능을 활성화합니다. 이는 서버 API가 여러 HTTP 동사(GET, PUT, POST, DELETE 등)를 처리하지만, 클라이언트가 특정 제약으로 인해 제한된 동사(예: GETPOST)만 사용할 수 있는 경우 유용할 수 있습니다. 예를 들어, 클라이언트가 X-Http-Method-Override 헤더를 DELETE로 설정하여 요청을 보내면, Ktor는 이 요청을 delete 라우트 핸들러를 사용하여 처리합니다.

의존성 추가

XHttpMethodOverride을(를) 사용하려면 빌드 스크립트에 ktor-server-method-override 아티팩트를 포함해야 합니다.

Kotlin
Groovy
XML

XHttpMethodOverride 설치

애플리케이션에 XHttpMethodOverride 플러그인을 설치하려면, 지정된

모듈
모듈을 사용하면 라우트를 그룹화하여 애플리케이션을 구조화할 수 있습니다.
install 함수에 전달하세요. 아래 코드 스니펫은 XHttpMethodOverride을(를) 설치하는 방법을 보여줍니다...

  • ... embeddedServer 함수 호출 내부.
  • ... Application 클래스의 확장 함수인 명시적으로 정의된 module 내부.
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.