I am implementing API routing using spring cloud gateway, in one of the use cases I need to get the header value from incoming request and use it for some processing, further add this processed value to outgoing (routed) API call as header. How to get the header value from an incoming API call in routeBuilder?
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder routeBuilder) {
return routeBuilder.routes()
.route(r -> r.path("/api/v1/**")
.setRequestHeader("testKey", "testValue")
.uri("URL"))
.build();
}
You Can write a custom filter for the same. Its just a way around, not sure what is the best way for doing this:
public class SomeFilterFactory
extends AbstractGatewayFilterFactory<SomeFilterFactory.SomeConfig> {
public SomeFilterFactory() {
super(SomeFilterFactory.SomeConfig.class);
}
@Override
public GatewayFilter apply(SomeFilterFactory.SomeConfig config) {
return (exchange, chain) -> {
ServerHttpRequest request = exchange.getRequest();
String someHeader = request.getHeaders().getFirst("someHeader");
// do your things here
return chain.filter(exchange);
};
}
public static class SomeConfig {
// your config if required
// or use name value config
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With