[release-branch.go1.3] net/http: fix double Content-Length in response

««« CL 105040043 / ef8878dbed3b
net/http: fix double Content-Length in response

Fixes #8180

LGTM=rsc
R=rsc
CC=golang-codereviews
https://golang.org/cl/105040043
»»»

TBR=bradfitz
R=golang-codereviews
CC=bradfitz, golang-codereviews, iant
https://golang.org/cl/102300046
This commit is contained in:
Russ Cox 2014-06-11 17:02:43 -04:00
parent 74183c5b06
commit 23f6bc5ed8
3 changed files with 23 additions and 2 deletions

View file

@ -266,7 +266,10 @@ func (r *Response) Write(w io.Writer) error {
return err
}
if r1.ContentLength == 0 && !chunked(r1.TransferEncoding) {
// 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 _, err := io.WriteString(w, "Content-Length: 0\r\n"); err != nil {
return err
}

View file

@ -191,6 +191,22 @@ func TestResponseWrite(t *testing.T) {
"Foo: Bar Baz\r\n" +
"\r\n",
},
// Want a single Content-Length header. Fixing issue 8180 where
// there were two.
{
Response{
StatusCode: StatusOK,
ProtoMajor: 1,
ProtoMinor: 1,
Request: &Request{Method: "POST"},
Header: Header{},
ContentLength: 0,
TransferEncoding: nil,
Body: nil,
},
"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n",
},
}
for i := range respWriteTests {

View file

@ -155,7 +155,9 @@ func (t *transferWriter) WriteHeader(w io.Writer) error {
// function of the sanitized field triple (Body, ContentLength,
// TransferEncoding)
if t.shouldSendContentLength() {
io.WriteString(w, "Content-Length: ")
if _, err := io.WriteString(w, "Content-Length: "); err != nil {
return err
}
if _, err := io.WriteString(w, strconv.FormatInt(t.ContentLength, 10)+"\r\n"); err != nil {
return err
}