Skip to content

Instantly share code, notes, and snippets.

@ptaylor
Created October 18, 2018 14:02
Show Gist options
  • Save ptaylor/311d0442ffd903f4725182031defd615 to your computer and use it in GitHub Desktop.
Save ptaylor/311d0442ffd903f4725182031defd615 to your computer and use it in GitHub Desktop.
Spring cloud gateway filter for adding the original gateway request URL
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());
};
}
}
@pinkninjajess
Copy link

Very helpful, thank you!

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