Spring Cloud Gateway: 4.1.0
I am looking for a basic requirement of extracting response body (READ-only operation - no modification) in one of the global post filters which gets executed after successful processing from redirected downstream endpoint.
I have gone through many articles over the internet and mostly found the suggested solution as reference implementation of org.springframework.cloud.gateway.filter.factory.rewrite.ModifyResponseBodyGatewayFilterFactory class. The implementation seems too complex to retrieve response body.
Then I referred following posts and managed to read the response body, however this also seems bit complex and does not fit in the execution order of implemented custom post filters (existing post filters are orders as 998, 999, 1000):
- How to get Original response body in Spring cloud gateway (Webflux) Post filter
- https://github.com/spring-cloud/spring-cloud-gateway/issues/1771
However, above implementation enforces following two hard limitations
- NettyWriteResponseFilter post filter (whose order is -1) must execute before custom post filter that reads response body. Due to this order of custom post filter has to be less than -1.
- The modified response object (even when the response body is not modified) from ServerHttpResponseDector has to be passed in the return statement as follows. Exchange object has to mutate even when response is not modified:
return chain.filter(exchange.mutate().response(logResponseBody(exchange)).build());
}
private ServerHttpResponseDecorator logResponseBody(final ServerWebExchange exchange) {
DataBufferFactory bufferFactory = exchange.getResponse().bufferFactory();
return new ServerHttpResponseDecorator(exchange.getResponse()) {
@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
...
}
}
}
Above implementation seems more inclined towards modifying the response body as the overridden method name is writeWith. However, the basic requirement is read-only operation here.
Is there any straight forward approach to just read only response body in global post filter? Any help/suggestion is much appreciated.