Skip to content

Commit

Permalink
Fixed HttpHelloWorldServerHandler for handling HTTP 1.0/1.1 (netty#9124)
Browse files Browse the repository at this point in the history
Motivation:

HttpHelloWorldServer example works incorrect for HTTP 1.1, the value of header connection is always set to close for each request.

Modification:

Correctly set header

Result:

Fixed HttpHelloWorldServerHandler for handling HTTP 1.0/1.1
  • Loading branch information
amizurov authored and normanmaurer committed May 8, 2019
1 parent 526f2da commit a74fead
Showing 1 changed file with 10 additions and 7 deletions.
Expand Up @@ -25,15 +25,14 @@
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.HttpVersion;

import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpHeaderValues.CLOSE;
import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE;
import static io.netty.handler.codec.http.HttpHeaderValues.TEXT_PLAIN;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

public class HttpHelloWorldServerHandler extends SimpleChannelInboundHandler<HttpObject> {
private static final byte[] CONTENT = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' };
Expand All @@ -49,12 +48,16 @@ public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
HttpRequest req = (HttpRequest) msg;

boolean keepAlive = HttpUtil.isKeepAlive(req);
FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
response.headers().set(CONTENT_TYPE, "text/plain");
response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());
FullHttpResponse response = new DefaultFullHttpResponse(req.protocolVersion(), OK,
Unpooled.wrappedBuffer(CONTENT));
response.headers()
.set(CONTENT_TYPE, TEXT_PLAIN)
.setInt(CONTENT_LENGTH, response.content().readableBytes());

if (keepAlive && req.protocolVersion().equals(HttpVersion.HTTP_1_0)) {
response.headers().set(CONNECTION, KEEP_ALIVE);
if (keepAlive) {
if (!req.protocolVersion().isKeepAliveDefault()) {
response.headers().set(CONNECTION, KEEP_ALIVE);
}
} else {
// Tell the client we're going to close the connection.
response.headers().set(CONNECTION, CLOSE);
Expand Down

0 comments on commit a74fead

Please sign in to comment.