1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package io.netty.example.http2.tiles;
18
19 import static io.netty.buffer.Unpooled.EMPTY_BUFFER;
20 import static io.netty.buffer.Unpooled.copiedBuffer;
21 import static io.netty.buffer.Unpooled.unreleasableBuffer;
22 import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
23 import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
24 import static io.netty.handler.codec.http.HttpResponseStatus.CONTINUE;
25 import static io.netty.handler.codec.http.HttpResponseStatus.OK;
26 import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
27 import static io.netty.util.CharsetUtil.UTF_8;
28 import io.netty.buffer.ByteBuf;
29 import io.netty.channel.ChannelFutureListener;
30 import io.netty.channel.ChannelHandlerContext;
31 import io.netty.channel.SimpleChannelInboundHandler;
32 import io.netty.handler.codec.http.DefaultFullHttpResponse;
33 import io.netty.handler.codec.http.FullHttpResponse;
34 import io.netty.handler.codec.http.HttpUtil;
35 import io.netty.handler.codec.http.HttpRequest;
36 import io.netty.handler.codec.http2.Http2CodecUtil;
37
38
39
40
41 public final class FallbackRequestHandler extends SimpleChannelInboundHandler<HttpRequest> {
42
43 private static final ByteBuf response = unreleasableBuffer(copiedBuffer("<!DOCTYPE html>"
44 + "<html><body><h2>To view the example you need a browser that supports HTTP/2 ("
45 + Http2CodecUtil.TLS_UPGRADE_PROTOCOL_NAME
46 + ")</h2></body></html>", UTF_8)).asReadOnly();
47
48 @Override
49 protected void channelRead0(ChannelHandlerContext ctx, HttpRequest req) throws Exception {
50 if (HttpUtil.is100ContinueExpected(req)) {
51 ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE, EMPTY_BUFFER));
52 }
53
54 ByteBuf content = ctx.alloc().buffer();
55 content.writeBytes(response.duplicate());
56
57 FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
58 response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
59 response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());
60
61 ctx.write(response).addListener(ChannelFutureListener.CLOSE);
62 }
63
64 @Override
65 public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
66 ctx.flush();
67 }
68
69 @Override
70 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
71 cause.printStackTrace();
72 ctx.close();
73 }
74 }