XHttpMethodOverride
필수 의존성: io.ktor:ktor-server-method-override
코드 예제: json-kotlinx-method-override
Native 서버Ktor는 Kotlin/Native를 지원하므로 추가 런타임이나 가상 머신 없이도 서버를 실행할 수 있습니다. 지원: ✅
XHttpMethodOverride 플러그인은 X-HTTP-Method-Override 헤더 내에 HTTP 메서드(verb)를 터널링하는 기능을 제공합니다. 이 기능은 서버 API가 여러 HTTP 메서드(GET, PUT, POST, DELETE 등)를 처리하지만, 클라이언트가 특정 제약으로 인해 제한된 메서드 세트(예: GET 및 POST)만 사용할 수 있는 경우 유용합니다. 예를 들어 클라이언트가 X-Http-Method-Override 헤더를 DELETE로 설정하여 요청을 보내면, Ktor는 delete 라우트 핸들러를 사용하여 해당 요청을 처리합니다.
의존성 추가
XHttpMethodOverride을(를) 사용하려면 빌드 스크립트에 ktor-server-method-override 아티팩트를 추가하세요:
implementation(ktorLibs.server.methodOverride)implementation ktorLibs.server.methodOverride<dependency>
<groupId>io.ktor</groupId>
<artifactId>ktor-server-method-override-jvm</artifactId>
<version>${ktor_version}</version>
</dependency>XHttpMethodOverride 설치
애플리케이션에 XHttpMethodOverride 플러그인을 설치하려면, 지정된 모듈모듈을 사용하면 라우트를 그룹화하여 애플리케이션의 구조를 설계할 수 있습니다.의 install 함수에 전달하세요. 다음 예제는 XHttpMethodOverride을(를) 설치하는 방법을 보여줍니다:
embeddedServer()함수 호출 내부.Application클래스에 명시적으로 정의된module()확장 함수 내부.
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.application.*
import io.ktor.server.plugins.methodoverride.*
fun main() {
embeddedServer(Netty, port = 8080) {
install(XHttpMethodOverride)
// ...
}.start(wait = true)
}import io.ktor.server.application.*
import io.ktor.server.plugins.methodoverride.*
// ...
fun Application.module() {
install(XHttpMethodOverride)
// ...
}XHttpMethodOverride 구성
기본적으로 XHttpMethodOverride은(는) X-Http-Method-Override 헤더를 확인하여 요청을 처리해야 하는 라우트를 결정합니다. headerName 프로퍼티를 사용하여 헤더 이름을 커스텀할 수 있습니다.
예제
아래의 HTTP 요청은 X-Http-Method-Override 헤더가 DELETE로 설정된 POST 메서드를 사용합니다:
POST http://0.0.0.0:8080/customer/3
X-Http-Method-Override: DELETEdelete 라우트 핸들러를 사용하여 이러한 요청을 처리하려면 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.
