Giter VIP home page Giter VIP logo

Comments (10)

WeirdBob avatar WeirdBob commented on May 14, 2024 7

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.

WeirdBob avatar WeirdBob commented on May 14, 2024 2

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.

WeirdBob avatar WeirdBob commented on May 14, 2024

Nevermind, I just added a GlobalFilter with an order of -2 and it works.

from spring-cloud-gateway.

re6exp avatar re6exp commented on May 14, 2024

I'm trying, but no result...
Would you please post any sample code how to change response body?

from spring-cloud-gateway.

re6exp avatar re6exp commented on May 14, 2024

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.

re6exp avatar re6exp commented on May 14, 2024

response.bufferFactory().allocateBuffer().asInputStream() reproduces nothing...

from spring-cloud-gateway.

re6exp avatar re6exp commented on May 14, 2024

Thank you very much!!!
I got hope!
You've made my day!!!

from spring-cloud-gateway.

re6exp avatar re6exp commented on May 14, 2024

We can simplify response body modification by using a plain GatewayFilter:

  1. Create GatewayFilter implementation with the same filter() content as in the sample above;
  2. Create method to return an instance of the filter, e.g., bodyToUppercase() (if you prefer - just for simplification);
  3. 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.

MarkZhang1111 avatar MarkZhang1111 commented on May 14, 2024

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.

MarkZhang1111 avatar MarkZhang1111 commented on May 14, 2024

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.