我一直在尝试使用 Spring Cloud Gateway,并且正在尝试修改响应正文。使用响应装饰器,我可以看到主体被修改,但是,缓冲区大小仍然是原始响应的大小。有没有办法将缓冲区大小扩展到新响应主体的大小?
public class ModifyBodyGatewayFilterImpl implements GatewayFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
logger.info("\n\nexchange.getAttributes():\n {}\n\n", exchange.getAttributes());
ServerHttpResponse response = exchange.getResponse();
DataBufferFactory dataBufferFactory = response.bufferFactory();
ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(response) {
@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
Flux<? extends DataBuffer> flux = (Flux<? extends DataBuffer>) body;
Flux<? extends DataBuffer> f = flux.flatMap( dataBuffer -> {
byte[] origRespContent = new byte[dataBuffer.readableByteCount()];
dataBuffer.read(origRespContent);
System.out.println("content::: " + (new String(origRespContent)));
//alocating a new buffer size does not help.
DataBuffer b = dataBufferFactory.allocateBuffer(256);
b.write("0123456789abcdefg".getBytes());
return Flux.just(b);
});
return super.writeWith(f);
}
};
ServerWebExchange swe = exchange.mutate().response(decoratedResponse).build();
return chain.filter(swe);
}
}
示例: 预期的重写响应为0123456789abcdefg
If original content is 11 bytes <p>test</p>
,则重写响应被截断为0123456789a
。