Home:ALL Converter>Micronaut application AWS Lambda - Http Requests and Responses filter

Micronaut application AWS Lambda - Http Requests and Responses filter

Ask Time:2022-08-13T04:38:22         Author:Comencau

Json Formatter

I am running a Micronaut app in an AWS Lambda as explained here : https://guides.micronaut.io/latest/mn-application-aws-lambda-java11.html

How am I supposed to implement a Request/Response filter ? I want a functionality like a good old Servlet filter. I read this documentation : https://docs.micronaut.io/latest/guide/#filters. Unfortunately it only consider the case where Micronaut is running in a Netty Http server context where we need to implement reactive way of doing to "not block the underlying Netty event loop". But here, I am running in a Lambda. Each of the incoming HTTP request will be handled by one Lambda instance and its Thread. I don't care about this reactive way of doing here. The need of a thread pool is replaced by Lambda.

I don't know what to do with this Publisher<MutableHttpResponse<?>>. I want the HTTP response directly.

@Filter("/**")
public class SecurityFilter implements HttpServerFilter {

Logger logger = LoggerFactory.getLogger(SecurityFilter.class);

@Override
public Publisher<MutableHttpResponse<?>> doFilter(HttpRequest<?> request, ServerFilterChain chain) {
    logger.debug("request = " + request);
    // Do something with HTTP request

    // Would like to call chain to go to the next Filter or to the Controller if no other filter
    // and have access to the HTTP Response like in a good old Servlet filter

    // What am I supposed to do with this response publisher. This app is running in AWS Lambda.
    // I don't have a netty http server. I don't need to protect "the underlying Netty event loop"
    // just want to have access to my Http Response here and be able to modify it (add headers for example)
    // in a synchronous manner without all this reactive stuff that I don't care about in this Lambda context

    Publisher<MutableHttpResponse<?>> responsePublisher = chain.proceed(request);
    responsePublisher.subscribe(new Subscriber<MutableHttpResponse<?>>() {
        @Override
        public void onSubscribe(Subscription s) {
            logger.debug("A");
        }

        @Override
        public void onNext(MutableHttpResponse<?> mutableHttpResponse) {
            logger.debug("response");
            logger.debug(mutableHttpResponse + "");
        }

        @Override
        public void onError(Throwable t) {
            logger.debug("B");
        }

        @Override
        public void onComplete() {
            logger.debug("C");
        }
    });

    return responsePublisher;
}

}

Author:Comencau,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/73339561/micronaut-application-aws-lambda-http-requests-and-responses-filter
yy