1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package io.netty5.example.http2.tiles;
18
19 import io.netty5.channel.ChannelHandlerContext;
20 import io.netty5.handler.codec.http.HttpObjectAggregator;
21 import io.netty5.handler.codec.http.HttpServerCodec;
22 import io.netty5.handler.codec.http2.DefaultHttp2Connection;
23 import io.netty5.handler.codec.http2.HttpToHttp2ConnectionHandlerBuilder;
24 import io.netty5.handler.codec.http2.InboundHttp2ToHttpAdapter;
25 import io.netty5.handler.codec.http2.InboundHttp2ToHttpAdapterBuilder;
26 import io.netty5.handler.ssl.ApplicationProtocolNames;
27 import io.netty5.handler.ssl.ApplicationProtocolNegotiationHandler;
28
29
30
31
32
33 public class Http2OrHttpHandler extends ApplicationProtocolNegotiationHandler {
34
35 private static final int MAX_CONTENT_LENGTH = 1024 * 100;
36
37 protected Http2OrHttpHandler() {
38 super(ApplicationProtocolNames.HTTP_1_1);
39 }
40
41 @Override
42 protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
43 if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
44 configureHttp2(ctx);
45 return;
46 }
47
48 if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
49 configureHttp1(ctx);
50 return;
51 }
52
53 throw new IllegalStateException("unknown protocol: " + protocol);
54 }
55
56 private static void configureHttp2(ChannelHandlerContext ctx) {
57 DefaultHttp2Connection connection = new DefaultHttp2Connection(true);
58 InboundHttp2ToHttpAdapter listener = new InboundHttp2ToHttpAdapterBuilder(connection)
59 .propagateSettings(true).validateHttpHeaders(false)
60 .maxContentLength(MAX_CONTENT_LENGTH).build();
61
62 ctx.pipeline().addLast(new HttpToHttp2ConnectionHandlerBuilder()
63 .frameListener(listener)
64
65 .connection(connection).build());
66
67 ctx.pipeline().addLast(new Http2RequestHandler());
68 }
69
70 private static void configureHttp1(ChannelHandlerContext ctx) throws Exception {
71 ctx.pipeline().addLast(new HttpServerCodec(),
72 new HttpObjectAggregator(MAX_CONTENT_LENGTH),
73 new FallbackRequestHandler());
74 }
75 }