1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.codec.http;
17
18 import io.netty.buffer.Unpooled;
19 import io.netty.channel.ChannelFutureListener;
20 import io.netty.channel.ChannelHandlerContext;
21 import io.netty.channel.ChannelInboundHandlerAdapter;
22 import io.netty.util.ReferenceCountUtil;
23
24 import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
25 import static io.netty.handler.codec.http.HttpResponseStatus.CONTINUE;
26 import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47 public class HttpServerExpectContinueHandler extends ChannelInboundHandlerAdapter {
48
49 private static final FullHttpResponse EXPECTATION_FAILED = new DefaultFullHttpResponse(
50 HTTP_1_1, HttpResponseStatus.EXPECTATION_FAILED, Unpooled.EMPTY_BUFFER);
51
52 private static final FullHttpResponse ACCEPT = new DefaultFullHttpResponse(
53 HTTP_1_1, CONTINUE, Unpooled.EMPTY_BUFFER);
54
55 static {
56 EXPECTATION_FAILED.headers().set(CONTENT_LENGTH, 0);
57 ACCEPT.headers().set(CONTENT_LENGTH, 0);
58 }
59
60
61
62
63
64 protected HttpResponse acceptMessage(@SuppressWarnings("unused") HttpRequest request) {
65 return ACCEPT.retainedDuplicate();
66 }
67
68
69
70
71 protected HttpResponse rejectResponse(@SuppressWarnings("unused") HttpRequest request) {
72 return EXPECTATION_FAILED.retainedDuplicate();
73 }
74
75 @Override
76 public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
77 if (msg instanceof HttpRequest) {
78 HttpRequest req = (HttpRequest) msg;
79
80 if (HttpUtil.is100ContinueExpected(req)) {
81 HttpResponse accept = acceptMessage(req);
82
83 if (accept == null) {
84
85 HttpResponse rejection = rejectResponse(req);
86 ReferenceCountUtil.release(msg);
87 ctx.writeAndFlush(rejection).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
88 return;
89 }
90
91 ctx.writeAndFlush(accept).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
92 req.headers().remove(HttpHeaderNames.EXPECT);
93 }
94 }
95 super.channelRead(ctx, msg);
96 }
97 }