Skip to content

Instantly share code, notes, and snippets.

@cho0o0
Created April 7, 2020 06:59
Show Gist options
  • Save cho0o0/d10bb4cb08ba9c4fb5183a06818e5d42 to your computer and use it in GitHub Desktop.
Save cho0o0/d10bb4cb08ba9c4fb5183a06818e5d42 to your computer and use it in GitHub Desktop.
Support X-HTTP-Method-Override Header in Spring WebFlux (Kotlin Version)
import org.springframework.http.HttpMethod
import org.springframework.http.server.reactive.ServerHttpRequest
import org.springframework.http.server.reactive.ServerHttpRequestDecorator
import org.springframework.stereotype.Component
import org.springframework.web.server.ServerWebExchange
import org.springframework.web.server.ServerWebExchangeDecorator
import org.springframework.web.server.WebFilter
import org.springframework.web.server.WebFilterChain
import reactor.core.publisher.Mono
/**
* This filter is used to modify request's HTTP Method if it was POST and owned a header named X-HTTP-Method-Override.
*/
@Component
class HttpMethodOverrideFilter: WebFilter {
override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> {
val request = exchange.request
val newMethod = request.headers["X-HTTP-Method-Override"]?.firstOrNull()?.let { HttpMethod.resolve(it.toUpperCase()) }
return if (newMethod != null && request.method == HttpMethod.POST) {
chain.filter(
NewExchange(exchange, newMethod)
)
} else {
chain.filter(exchange)
}
}
}
private class NewExchange(exchange: ServerWebExchange, private val httpMethod: HttpMethod) : ServerWebExchangeDecorator(exchange) {
override fun getRequest(): ServerHttpRequest {
return object : ServerHttpRequestDecorator(this.delegate.request) {
override fun getMethodValue(): String = httpMethod.name
override fun getMethod(): HttpMethod = httpMethod
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment