Commit 88ccb3c9 authored by Matt Layher's avatar Matt Layher Committed by Brad Fitzpatrick

net/http: omit Content-Length in Response.Write for 1xx or 204 status

Per RFC 7230, 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).".

Fixes #16942

Change-Id: I8006c76c126304e13618966e6eafb08a3885d3cd
Reviewed-on: https://go-review.googlesource.com/28351Reviewed-by: 's avatarBrad Fitzpatrick <bradfitz@golang.org>
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
parent 8895a99c
......@@ -300,7 +300,7 @@ func (r *Response) Write(w io.Writer) error {
// contentLengthAlreadySent may have been already sent for
// POST/PUT requests, even if zero length. See Issue 8180.
contentLengthAlreadySent := tw.shouldSendContentLength()
if r1.ContentLength == 0 && !chunked(r1.TransferEncoding) && !contentLengthAlreadySent {
if r1.ContentLength == 0 && !chunked(r1.TransferEncoding) && !contentLengthAlreadySent && bodyAllowedForStatus(r.StatusCode) {
if _, err := io.WriteString(w, "Content-Length: 0\r\n"); err != nil {
return err
}
......
......@@ -241,7 +241,8 @@ func TestResponseWrite(t *testing.T) {
"HTTP/1.0 007 license to violate specs\r\nContent-Length: 0\r\n\r\n",
},
// No stutter.
// No stutter. Status code in 1xx range response should
// not include a Content-Length header. See issue #16942.
{
Response{
StatusCode: 123,
......@@ -253,7 +254,23 @@ func TestResponseWrite(t *testing.T) {
Body: nil,
},
"HTTP/1.0 123 Sesame Street\r\nContent-Length: 0\r\n\r\n",
"HTTP/1.0 123 Sesame Street\r\n\r\n",
},
// Status code 204 (No content) response should not include a
// Content-Length header. See issue #16942.
{
Response{
StatusCode: 204,
Status: "No Content",
ProtoMajor: 1,
ProtoMinor: 0,
Request: dummyReq("GET"),
Header: Header{},
Body: nil,
},
"HTTP/1.0 204 No Content\r\n\r\n",
},
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment