Skip to content

Instantly share code, notes, and snippets.

@dalegaspi
Created April 22, 2021 23:11
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dalegaspi/df8f5bf25fe25440f35684fd14d98a60 to your computer and use it in GitHub Desktop.
Save dalegaspi/df8f5bf25fe25440f35684fd14d98a60 to your computer and use it in GitHub Desktop.
Custom Spring Cloud Gateway to change HTTP Method In Flight
spring:
application:
name: nobody
cloud:
gateway:
httpclient:
wiretap: true
response-timeout: 6s
httpserver:
wiretap: true
routes:
- id: sample
uri: http://httpbin.org
predicates:
- Method=PUT
- Path=/what
filters:
- SetPath=/anything/blaaaah
- ConvertHttpMethod=POST # converts PUT to POST
package yeet;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
@Slf4j
@Component
public class ConvertHttpMethodFilter extends AbstractGatewayFilterFactor<ConvertHttpMethodFilter.Config> {
public ConvertHttpMethodFilter() {
super(Config.class);
}
static final String REPLACEMENT_KEY = "replacement";
@Override
public List<String> shortcutFieldOrder() {
return Arrays.asList(REPLACEMENT_KEY);
}
@Override
public GatewayFilter apply(Config config) {
return (exchange, chain) -> {
var request = exchange.getRequest();
log.debug("changing method from {} to {}", request.getMethod().toString(),
config.getReplacement().toString());
var mutatedExchange = exchange.mutate().request(request.mutate().method(config.getReplacement()).build())
.build();
return chain.filter(mutatedExchange);
};
}
@Override
public String name() {
return "ConvertHttpMethod";
}
public static class Config {
private HttpMethod replacement;
public HttpMethod getReplacement() {
return replacement;
}
public void setReplacement(String method) {
this.replacement = HttpMethod.resolve(method);
assert this.replacement != null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment