Skip to content

Instantly share code, notes, and snippets.

@omidp
Created December 12, 2021 10:06
Show Gist options
  • Save omidp/e4d247a16897c629f10eb8701346074f to your computer and use it in GitHub Desktop.
Save omidp/e4d247a16897c629f10eb8701346074f to your computer and use it in GitHub Desktop.
spring cloud gateway http method filter
package com.cloud.gateway.app;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.setResponseStatus;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.support.HttpStatusHolder;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;
/**
* @author omidp
*
*/
@Component
@Slf4j
public class HttpMethodGatewayFilter extends AbstractGatewayFilterFactory<HttpMethodGatewayFilter.Config> {
public HttpMethodGatewayFilter() {
super(Config.class);
}
public static class Config {
}
@Override
public GatewayFilter apply(Config config) {
return new GatewayFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest req = exchange.getRequest();
if (HttpMethod.POST.equals(req.getMethod()) == false) {
if (!exchange.getResponse().isCommitted()) {
setResponseStatus(exchange, new HttpStatusHolder(HttpStatus.I_AM_A_TEAPOT, null));
final ServerHttpResponse response = exchange.getResponse();
return response.setComplete();
}
return Mono.empty();
} else {
Object httpMethod = req.getHeaders().get("action");
if (httpMethod != null) {
log.info("httpMethod action header {}", httpMethod);
var mutatedExchange = exchange.mutate().request(req.mutate().method(HttpMethod.GET).build())
.build();
return chain.filter(mutatedExchange);
}
ServerHttpRequest request = req.mutate().build();
return chain.filter(exchange.mutate().request(request).build());
}
}
};
}
}
@omidp
Copy link
Author

omidp commented Dec 12, 2021

spring:
cloud:
gateway:
routes:
- id: user-service
uri: lb://USER-SERVICE
predicates:
- Path=/user/**
filters:
- HttpMethodGatewayFilter
- RewritePath=/user/(?.*), /${path}
- name: CircuitBreaker
args:
name: cloudCircuitBreaker
fallbackUri: forward:/fallback

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment