1

Integrating Resteasy in my netty 4 + Guice application works perfectly using server adapter provided by Resteasy (great job guys).

Now my JAX-RS server runs on a different port as my HTTP server (also based on Netty).

So, I need to implement Cross Origin Resource Sharing (CORS) on my Resteasy server by adding following HTTP headers to the response:

Access-Control-Allow-Origin : *
Access-Control-Allow-Methods : GET,POST,PUT,DELETE,OPTIONS
Access-Control-Allow-Headers : X-Requested-With, Content-Type, Content-Length

For now, I have forked NettyJaxrsServer and RestEasyHttpResponseEncoder classes and it works quite good (but not a very "clean" solution to me).

I just wonder how to add those headers to response using something like a customized encoder that I could add to my Netty pipeline (or something else...)

Thanks.

4

1 回答 1

3

解决方案:像这样创建一个 SimpleChannelInboundHandler:

public class CorsHeadersChannelHandler extends SimpleChannelInboundHandler<NettyHttpRequest> {
    protected void channelRead0(ChannelHandlerContext ctx, NettyHttpRequest request) throws Exception {
        request.getResponse().getOutputHeaders().add("Access-Control-Allow-Origin", "*");
        request.getResponse().getOutputHeaders().add("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
        request.getResponse().getOutputHeaders().add("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Content-Length");

        ctx.fireChannelRead(request);
    }
}

并在 RestEasyHttpResponseEncoder 之前将其添加到 Netty 管道。

注意:最后我在现有的 Netty Http 服务器管道的末尾添加了 RestEasyHttpRequestDecoder、RestEasyHttpResponseEncoder 和 RequestHandler,所以我不再需要 CORS 标头了。

于 2013-09-21T17:05:51.400 回答