Created
April 22, 2021 23:11
-
-
Save dalegaspi/df8f5bf25fe25440f35684fd14d98a60 to your computer and use it in GitHub Desktop.
Custom Spring Cloud Gateway to change HTTP Method In Flight
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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