Skip to content

Commit 23f6bc5

Browse files
committed
[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
1 parent 74183c5 commit 23f6bc5

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

src/pkg/net/http/response.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,10 @@ func (r *Response) Write(w io.Writer) error {
266266
return err
267267
}
268268

269-
if r1.ContentLength == 0 && !chunked(r1.TransferEncoding) {
269+
// contentLengthAlreadySent may have been already sent for
270+
// POST/PUT requests, even if zero length. See Issue 8180.
271+
contentLengthAlreadySent := tw.shouldSendContentLength()
272+
if r1.ContentLength == 0 && !chunked(r1.TransferEncoding) && !contentLengthAlreadySent {
270273
if _, err := io.WriteString(w, "Content-Length: 0\r\n"); err != nil {
271274
return err
272275
}

src/pkg/net/http/responsewrite_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,22 @@ func TestResponseWrite(t *testing.T) {
191191
"Foo: Bar Baz\r\n" +
192192
"\r\n",
193193
},
194+
195+
// Want a single Content-Length header. Fixing issue 8180 where
196+
// there were two.
197+
{
198+
Response{
199+
StatusCode: StatusOK,
200+
ProtoMajor: 1,
201+
ProtoMinor: 1,
202+
Request: &Request{Method: "POST"},
203+
Header: Header{},
204+
ContentLength: 0,
205+
TransferEncoding: nil,
206+
Body: nil,
207+
},
208+
"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n",
209+
},
194210
}
195211

196212
for i := range respWriteTests {

src/pkg/net/http/transfer.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,9 @@ func (t *transferWriter) WriteHeader(w io.Writer) error {
155155
// function of the sanitized field triple (Body, ContentLength,
156156
// TransferEncoding)
157157
if t.shouldSendContentLength() {
158-
io.WriteString(w, "Content-Length: ")
158+
if _, err := io.WriteString(w, "Content-Length: "); err != nil {
159+
return err
160+
}
159161
if _, err := io.WriteString(w, strconv.FormatInt(t.ContentLength, 10)+"\r\n"); err != nil {
160162
return err
161163
}

0 commit comments

Comments
 (0)