1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.testsuite.http2;
17
18 import io.netty.buffer.ByteBuf;
19 import io.netty.buffer.ByteBufUtil;
20 import io.netty.channel.ChannelFutureListener;
21 import io.netty.channel.ChannelHandlerContext;
22 import io.netty.channel.SimpleChannelInboundHandler;
23 import io.netty.handler.codec.http.DefaultFullHttpResponse;
24 import io.netty.handler.codec.http.FullHttpRequest;
25 import io.netty.handler.codec.http.FullHttpResponse;
26 import io.netty.handler.codec.http.HttpHeaderValues;
27 import io.netty.handler.codec.http.HttpUtil;
28
29 import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
30 import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
31 import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
32 import static io.netty.handler.codec.http.HttpResponseStatus.CONTINUE;
33 import static io.netty.handler.codec.http.HttpResponseStatus.OK;
34 import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
35 import static io.netty.util.internal.ObjectUtil.checkNotNull;
36
37
38
39
40 public class HelloWorldHttp1Handler extends SimpleChannelInboundHandler<FullHttpRequest> {
41 private final String establishApproach;
42
43 HelloWorldHttp1Handler(String establishApproach) {
44 this.establishApproach = checkNotNull(establishApproach, "establishApproach");
45 }
46
47 @Override
48 public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
49 if (HttpUtil.is100ContinueExpected(req)) {
50 ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE, ctx.alloc().buffer(0)));
51 }
52 boolean keepAlive = HttpUtil.isKeepAlive(req);
53
54 ByteBuf content = ctx.alloc().buffer();
55 content.writeBytes(HelloWorldHttp2Handler.RESPONSE_BYTES.duplicate());
56 ByteBufUtil.writeAscii(content, " - via " + req.protocolVersion() + " (" + establishApproach + ")");
57
58 FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
59 response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
60 response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());
61
62 if (!keepAlive) {
63 ctx.write(response).addListener(ChannelFutureListener.CLOSE);
64 } else {
65 response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
66 ctx.write(response);
67 }
68 }
69
70 @Override
71 public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
72 ctx.flush();
73 }
74
75 @Override
76 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
77 cause.printStackTrace();
78 ctx.close();
79 }
80 }