Comments (10)
Hi,
I'll try to make a Gist to show you how I've done (I'll have to clean up corporate code first), but in short:
- implement GlobalFilter & Ordered
- important: the order has to be <-1 or else the standard NettyWriteResponseFilter will send the response before your filter gets a chance to be called
- in the overriden filter method, create a ServerHttpResponseDecorator over exchange.getResponse(), override the writeWith method of this decorator and do your body modifications there (I had to cast the body from a Publisher<? extends DataBuffer> to a Flux to make it easier to modify), return super.writeWith(yourModifiedBodyFlux). Mutate the exchange and set your decorator as the new response.
Hope it makes sense. I have 2 filters that work that way (the first one removes some fields from the JSON response, the second one ciphers the body of the response in AES).
Not the cleanest code I've written though, maybe there is a better way.
from spring-cloud-gateway.
I made a small example here : https://gist.github.com/WeirdBob/b25569d461f0f54444d2c0eab51f3c48
it just converts the body into to uppercase.
you can launch it and try going to localhost:8080/uuid
from spring-cloud-gateway.
Nevermind, I just added a GlobalFilter with an order of -2 and it works.
from spring-cloud-gateway.
I'm trying, but no result...
Would you please post any sample code how to change response body?
from spring-cloud-gateway.
Thanks a lot!
I'm new to reactive way, so I have to learn many things "in parallel mode" in short time...
And how do you cast the body from a Publisher<? extends DataBuffer> to a Flux?
I got it "works" somehow, but always with exception "only one subscriber allowed". And that way, as I understand, is wrong.
from spring-cloud-gateway.
response.bufferFactory().allocateBuffer().asInputStream() reproduces nothing...
from spring-cloud-gateway.
Thank you very much!!!
I got hope!
You've made my day!!!
from spring-cloud-gateway.
We can simplify response body modification by using a plain GatewayFilter
:
- Create
GatewayFilter
implementation with the samefilter()
content as in the sample above; - Create method to return an instance of the filter, e.g.,
bodyToUppercase()
(if you prefer - just for simplification); - Add filter to the router like:
.route("routeIdHere")
.predicate(path("/deep/deep/hurray"))
...
.filter(bodyToUppercase(), NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER - 1)
...
.uri("lb://serverId")
So, it can be achieved with a plain GatewayFilter, by forcing the order
pass. Using the GlobalFilter is not mandatory, but using GatewayFilter
we have clear picture of the routes.
from spring-cloud-gateway.
How to append or modify the request body ? the length of the body may become longer, but the service behind the gateway received the request body have been truncated, some data lost.
from spring-cloud-gateway.
I solved this problem by modifying the length of the head:
To modify the header CONTENT_LENGTH,You must to create a new HttpHeaders, and then copy the orignal values and remove the CONTENT_LENGTH, add the correct length(If you do not do this , the request body will be truncated if you modify the request body and the body become longer )
HttpHeaders myHeaders = new HttpHeaders();
copyMultiValueMap(request.getHeaders(), myHeaders);
myHeaders.remove(HttpHeaders.CONTENT_LENGTH);
myHeaders.set(HttpHeaders.CONTENT_LENGTH, String.valueOf(len));
Flux<DataBuffer> bodyFlux = Flux.just(bodyDataBuffer);
newRequest = new ServerHttpRequestDecorator(newRequest) {
@Override
public Flux<DataBuffer> getBody() {
return bodyFlux;
}
@Override
public HttpHeaders getHeaders() {
return myHeaders;
}
};
private static <K, V> void copyMultiValueMap(MultiValueMap<K,V> source, MultiValueMap<K,V> target) {
source.forEach((key, value) -> target.put(key, new LinkedList<>(value)));
}
from spring-cloud-gateway.
Related Issues (20)
- [Gateway MVC] Transfer-Encoding added to GET/HEAD requests, causing some WAF errors HOT 1
- [Gateway MVC] ERR_HTTP2_PROTOCOL_ERROR if HTTP/2 enabled HOT 1
- Adding circuitBreaker filter in mvc throws IllegalArgumentException HOT 1
- formFilter append useless character "&" cause body length change HOT 2
- MVC Server: Options to create routes automatically from service registry HOT 2
- Class 'org.springframework.cloud.gateway.route.builder.RouteDslKt' is compiled by a pre-release version of Kotlin and cannot be loaded by this version of the compiler HOT 4
- Unable to handle exceptions using @ControllerAdvice and @ExceptionHandler in mvc gateway HOT 3
- Gateway MVC: Retry filter sends empty body when retrying POST/PUT/etc HOT 4
- server-mvc properties are not included in documentation
- [spring-cloud-gateway-mvc] forward operation has side affects HOT 2
- Add support for multiple proto files in one descriptor for JsonToGrpcGatewayFilterFactory HOT 3
- Gateway issue with image upload. HOT 3
- Spring Cloud Gateway Server MVC rateLimit filter(Bucket4jFilter) will got UnsupportedOperationException when response headers is ReadOnlyHttpHeaders HOT 2
- Gateway MVC forward request but with decoded parameters (%2B becomes +)
- "spring.cloud.gateway.requests" metric not incremented for subsequent cached responses
- Question migrate Apache httpd to spring gateway HOT 6
- 500 when CORS and CircuitBreaker are aplied to the same route HOT 9
- Global exception handling with Spring Cloud Gateway MVC HOT 1
- the gateway can modify the queryparams of the URL by Get request? HOT 4
- X-Forwarded-Prefix not working when using MVC
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from spring-cloud-gateway.