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.buffer.api.Buffer;
20 import io.netty5.channel.ChannelFutureListeners;
21 import io.netty5.channel.ChannelHandlerContext;
22 import io.netty5.channel.SimpleChannelInboundHandler;
23 import io.netty5.handler.codec.http.DefaultFullHttpResponse;
24 import io.netty5.handler.codec.http.FullHttpResponse;
25 import io.netty5.handler.codec.http.HttpRequest;
26 import io.netty5.handler.codec.http.HttpUtil;
27 import io.netty5.handler.codec.http2.Http2CodecUtil;
28
29 import java.nio.charset.StandardCharsets;
30
31 import static io.netty5.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
32 import static io.netty5.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
33 import static io.netty5.handler.codec.http.HttpResponseStatus.CONTINUE;
34 import static io.netty5.handler.codec.http.HttpResponseStatus.OK;
35 import static io.netty5.handler.codec.http.HttpVersion.HTTP_1_1;
36
37
38
39
40 public final class FallbackRequestHandler extends SimpleChannelInboundHandler<HttpRequest> {
41
42 private static final byte[] responseBytes = ("<!DOCTYPE html>"
43 + "<html><body><h2>To view the example you need a browser that supports HTTP/2 ("
44 + Http2CodecUtil.TLS_UPGRADE_PROTOCOL_NAME
45 + ")</h2></body></html>").getBytes(StandardCharsets.UTF_8);
46
47 @Override
48 protected void messageReceived(ChannelHandlerContext ctx, HttpRequest req) throws Exception {
49 if (HttpUtil.is100ContinueExpected(req)) {
50 ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE, ctx.bufferAllocator().allocate(0)));
51 }
52
53 Buffer content = ctx.bufferAllocator().allocate(responseBytes.length).writeBytes(responseBytes);
54
55 FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
56 response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
57 response.headers().setInt(CONTENT_LENGTH, response.payload().readableBytes());
58
59 ctx.write(response).addListener(ctx, ChannelFutureListeners.CLOSE);
60 }
61
62 @Override
63 public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
64 ctx.flush();
65 }
66
67 @Override
68 public void channelExceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
69 cause.printStackTrace();
70 ctx.close();
71 }
72 }