0
votes

How to do the following with netty:

  1. if uri starts "/static/*" path use StaticHttpHandler
  2. if other uri uses HttpHandler
  3. if "/ws" use WebSocketHandler

Now I have this code:

public class HttpHelloWorldServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    public void initChannel(SocketChannel ch) {
        ChannelPipeline p = ch.pipeline();
        p.addLast(new HttpServerCodec());
        p.addLast(new HttpHandler());

        // Other pipelene handlers?
    }
}

Can I use something like "swither" in pipeline? Or it doesn't make sense and I need to handle request uri inside handler. But how to determine websocket protocol?

1

1 Answers

3
votes

In your own HttpHandler, you have to check the uri first and then decide which "real" handler to run. To do that, 2 ways of doing it:

  • either you have in your business code (HttpHandler) the necessary objects already alocated or newly allocated (StaticHttpHandler and WebSocketHandler) and then pass the request manually to them by calling them explicitely (so they are no more "standard" Netty handler)
  • either you have one specific handler (HttpRouteHandler for instance) that decides which handler to add to the pipeline for this request and pass to the next one the current request

The first is simplest but not easy to extend.

The second is a bit harder and you have to be sure/clean that each request is getting to the right handler. For instance,

  • once a channel is connected, are all requests coming into it of the very same nature ? If so, then you can safely add the necessary handler and even removes the HttpRouteHandler.
  • if not, then for each request, you have to decide to add/remove the necessary handlers as needed, keeping the HttpRouteHandler in the pipeline to handle the new context

Saying it short, you're trying to implement a route resolution in a web service.