Skip to content

Commit

Permalink
Merge pull request #2393 from chenBright/fix_http_no_content
Browse files Browse the repository at this point in the history
Fix HTTP no content of 1xx and 204
Huixxi authored Sep 29, 2023

Unverified

The committer email address is not verified.
2 parents 09f0916 + ae116d6 commit 28e44a0
Showing 2 changed files with 19 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/brpc/details/http_message.cpp
Original file line number Diff line number Diff line change
@@ -630,7 +630,19 @@ void MakeRawHttpResponse(butil::IOBuf* response,
os << "HTTP/" << h->major_version() << '.'
<< h->minor_version() << ' ' << h->status_code()
<< ' ' << h->reason_phrase() << BRPC_CRLF;
if (content) {
bool is_invalid_content = h->status_code() < HTTP_STATUS_OK ||
h->status_code() == HTTP_STATUS_NO_CONTENT;
if (is_invalid_content) {
// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.1
// A server MUST NOT send a Transfer-Encoding header field in any
// response with a status code of 1xx (Informational) or 204 (No
// Content).
h->RemoveHeader("Transfer-Encoding");
// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2
// A server MUST NOT send a Content-Length header field in any response
// with a status code of 1xx (Informational) or 204 (No Content).
h->RemoveHeader("Content-Length");
} else if (content) {
h->RemoveHeader("Content-Length");
// Never use "Content-Length" set by user.
// Always set Content-Length since lighttpd requires the header to be
@@ -647,7 +659,7 @@ void MakeRawHttpResponse(butil::IOBuf* response,
}
os << BRPC_CRLF; // CRLF before content
os.move_to(*response);
if (content) {
if (!is_invalid_content && content) {
response->append(butil::IOBuf::Movable(*content));
}
}
5 changes: 5 additions & 0 deletions test/brpc_http_message_unittest.cpp
Original file line number Diff line number Diff line change
@@ -435,6 +435,11 @@ TEST(HttpMessageTest, serialize_http_response) {
content.append("data2");
MakeRawHttpResponse(&response, &header, &content);
ASSERT_EQ("HTTP/1.1 200 OK\r\nContent-Length: 5\r\nFoo: Bar\r\n\r\ndata2", response);

header.SetHeader("Transfer-Encoding", "chunked");
header.set_status_code(brpc::HTTP_STATUS_NO_CONTENT);
MakeRawHttpResponse(&response, &header, &content);
ASSERT_EQ("HTTP/1.1 204 No Content\r\nFoo: Bar\r\n\r\n", response);
}

} //namespace

0 comments on commit 28e44a0

Please sign in to comment.