0
public class FileBrowserPostFilter implements GatewayFilter, Ordered {
    @Autowired
    private Gson gson;

    @Autowired
    private FileBrowserService fileBrowserService;

    @Override
    public int getOrder() {
        return 100;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        return chain.filter(exchange)
                .then(Mono.fromRunnable(() -> {
                    var request = exchange.getRequest();
                    var response = exchange.getResponse();
                    String requestMethod = request.getMethod().name().toUpperCase();
                    var status = response.getStatusCode();

                    if (requestMethod.equals("POST") && status.is2xxSuccessful()) {
                        String path = request.getPath().subPath(4).value();
                        var newItem = this.fileBrowserService.getItem(path);
                        var newItemJson = this.gson.toJson(newItem);
                        response.setRawStatusCode(201);
                        DataBuffer dataBuffer = response.bufferFactory()
                                .wrap(newItemJson.getBytes(StandardCharsets.UTF_8));
                        response.writeWith(Mono.just(dataBuffer));
                        exchange.mutate().response(response).build();
                    }
                }));
    }
}

asume fileBrowserService will always return a valid item I am expecting the filter to change status code to 201 (successful) modify the response body to something like so:

{
        "id": 1,
        "path": "/1/name.jpg",
        "name": "name.jpg",
        "size": 503627,
        "extension": ".jpg",
        "modified": "2023-07-12T11:55:22.440578974-04:00",
        "mode": 493,
        "type": "image",
        "sharedUsers": [],
        "public": false,
        "dir": false,
        "symlink": false
    }

but it keep returning it original response body

200 ok

which should not happening does anyone know why?

I have try all these solution here https://wankhedeshubham.medium.com/spring-cloud-gateway-modify-response-body-using-global-post-filter-1dbe0a077f8e Spring Cloud Gateway - modify response body in global Post filter and it is not working.

  • You're trying to modify the HTTP response after the response *has already been committed*, which can't be done. You need to handle it at the `pre` or `post` phase intstead, by intercepting the response before it's sent back to the client – Yahor Barkouski Jul 12 '23 at 16:25
  • I thought Mono.fromrunable is Handle in post phase? How should I access this post phase before commit? – vincent bui Jul 12 '23 at 17:15
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Jul 13 '23 at 17:55

0 Answers0