1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty5.handler.codec.http;
17
18 import io.netty5.buffer.api.Buffer;
19
20 import static io.netty5.handler.codec.http.HttpConstants.SP;
21
22
23
24
25 public class HttpResponseEncoder extends HttpObjectEncoder<HttpResponse> {
26
27 @Override
28 public boolean acceptOutboundMessage(Object msg) throws Exception {
29 return super.acceptOutboundMessage(msg) && !(msg instanceof HttpRequest);
30 }
31
32 @Override
33 protected void encodeInitialLine(Buffer buf, HttpResponse response) throws Exception {
34 response.protocolVersion().encode(buf);
35 buf.writeByte(SP);
36 response.status().encode(buf);
37 buf.writeShort(CRLF_SHORT);
38 }
39
40 @Override
41 protected void sanitizeHeadersBeforeEncode(HttpResponse msg, boolean isAlwaysEmpty) {
42 if (isAlwaysEmpty) {
43 HttpResponseStatus status = msg.status();
44 if (status.codeClass() == HttpStatusClass.INFORMATIONAL ||
45 status.code() == HttpResponseStatus.NO_CONTENT.code()) {
46
47
48
49 msg.headers().remove(HttpHeaderNames.CONTENT_LENGTH);
50
51
52
53 msg.headers().remove(HttpHeaderNames.TRANSFER_ENCODING);
54 } else if (status.code() == HttpResponseStatus.RESET_CONTENT.code()) {
55
56
57 msg.headers().remove(HttpHeaderNames.TRANSFER_ENCODING);
58
59
60
61 msg.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, 0);
62 }
63 }
64 }
65
66 @Override
67 protected boolean isContentAlwaysEmpty(HttpResponse msg) {
68
69
70 HttpResponseStatus status = msg.status();
71
72 if (status.codeClass() == HttpStatusClass.INFORMATIONAL) {
73
74 if (status.code() == HttpResponseStatus.SWITCHING_PROTOCOLS.code()) {
75
76
77
78 return msg.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_VERSION);
79 }
80 return true;
81 }
82 return status.code() == HttpResponseStatus.NO_CONTENT.code() ||
83 status.code() == HttpResponseStatus.NOT_MODIFIED.code() ||
84 status.code() == HttpResponseStatus.RESET_CONTENT.code();
85 }
86 }