Skip to content

Commit

Permalink
Fix HTTP no content of 1xx and 204
Browse files Browse the repository at this point in the history
  • Loading branch information
chenBright committed Sep 25, 2023
1 parent 09f0916 commit be19c28
Show file tree
Hide file tree
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
Expand Up @@ -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 no_content = h->status_code() < HTTP_STATUS_OK ||
h->status_code() == HTTP_STATUS_NO_CONTENT;
if (no_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
Expand All @@ -647,7 +659,7 @@ void MakeRawHttpResponse(butil::IOBuf* response,
}
os << BRPC_CRLF; // CRLF before content
os.move_to(*response);
if (content) {
if (!no_content && content) {
response->append(butil::IOBuf::Movable(*content));
}
}
Expand Down
5 changes: 5 additions & 0 deletions test/brpc_http_message_unittest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 be19c28

Please sign in to comment.