Commit 632778c3 authored by Peter Waldschmidt's avatar Peter Waldschmidt Committed by Brad Fitzpatrick

net/http: Don't set Content-Length: -1 when responding to a POST

Fixes an issue where Response.Write writes out a Content-Length: -1
header when the corresponding Request is a POST or PUT and the
ContentLength was not previously set.

This was encountered when using httputil.DumpResponse
to write out the response from a server that responded to a PUT
request with no Content-Length header. The dumped output is
thus invalid.

Change-Id: I52c6ae8ef3443f1f9de92aeee9f9581dabb05991
Reviewed-on: https://go-review.googlesource.com/9496Reviewed-by: 's avatarBrad Fitzpatrick <bradfitz@golang.org>
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
parent afd2d2b6
......@@ -207,6 +207,21 @@ func TestResponseWrite(t *testing.T) {
},
"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n",
},
// When a response to a POST has Content-Length: -1, make sure we don't
// write the Content-Length as -1.
{
Response{
StatusCode: StatusOK,
ProtoMajor: 1,
ProtoMinor: 1,
Request: &Request{Method: "POST"},
Header: Header{},
ContentLength: -1,
Body: ioutil.NopCloser(strings.NewReader("abcdef")),
},
"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\nabcdef",
},
}
for i := range respWriteTests {
......
......@@ -138,6 +138,9 @@ func (t *transferWriter) shouldSendContentLength() bool {
if t.ContentLength > 0 {
return true
}
if t.ContentLength < 0 {
return false
}
// Many servers expect a Content-Length for these methods
if t.Method == "POST" || t.Method == "PUT" {
return true
......
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