Created
October 18, 2018 14:02
-
-
Save ptaylor/311d0442ffd903f4725182031defd615 to your computer and use it in GitHub Desktop.
Spring cloud gateway filter for adding the original gateway request URL
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 org.example; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import org.springframework.cloud.gateway.filter.GatewayFilter; | |
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; | |
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils; | |
import org.springframework.http.server.reactive.ServerHttpRequest; | |
import org.springframework.stereotype.Component; | |
import java.net.URI; | |
import java.util.LinkedHashSet; | |
import java.util.Optional; | |
/** | |
* Filter to add the original gateway URL to the request as a header. | |
*/ | |
@Component | |
public class AddOriginalUrlFilterFactory extends AbstractGatewayFilterFactory { | |
Logger log = LoggerFactory.getLogger(AddOriginalUrlFilterFactory.class); | |
@Override | |
public GatewayFilter apply(Object config) { | |
return (exchange, chain) -> { | |
LinkedHashSet<URI> attr = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR); | |
Optional<URI> option = attr.stream().findFirst(); | |
ServerHttpRequest request = exchange.getRequest(); | |
if (option.isPresent()) { | |
String originalUrl = option.get().toString(); | |
log.info("Adding original request URL: {}", originalUrl); | |
request = request.mutate().header("X-Gateway-Original-Request-Url", originalUrl).build(); | |
} | |
return chain.filter(exchange.mutate().request(request).build()); | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very helpful, thank you!