return ioutil.NopCloser(&r), nil
}
default:
- if body != NoBody {
- req.ContentLength = -1 // unknown
- }
+ // This is where we'd set it to -1 (at least
+ // if body != NoBody) to mean unknown, but
+ // that broke people during the Go 1.8 testing
+ // period. People depend on it being 0 I
+ // guess. Maybe retry later. See Issue 18117.
}
// For client requests, Request.ContentLength of 0
// means either actually 0, or unknown. The only way
// so we use a well-known ReadCloser variable instead
// and have the http package also treat that sentinel
// variable to mean explicitly zero.
- if req.ContentLength == 0 {
+ if req.GetBody != nil && req.ContentLength == 0 {
req.Body = NoBody
req.GetBody = func() (io.ReadCloser, error) { return NoBody, nil }
}
{bytes.NewBuffer([]byte("1234")), 4},
{strings.NewReader("12345"), 5},
{strings.NewReader(""), 0},
- // Not detected:
- {struct{ io.Reader }{strings.NewReader("xyz")}, -1},
- {io.NewSectionReader(strings.NewReader("x"), 0, 6), -1},
- {readByte(io.NewSectionReader(strings.NewReader("xy"), 0, 6)), -1},
+ {NoBody, 0},
+
+ // Not detected. During Go 1.8 we tried to make these set to -1, but
+ // due to Issue 18117, we keep these returning 0, even though they're
+ // unknown.
+ {struct{ io.Reader }{strings.NewReader("xyz")}, 0},
+ {io.NewSectionReader(strings.NewReader("x"), 0, 6), 0},
+ {readByte(io.NewSectionReader(strings.NewReader("xy"), 0, 6)), 0},
}
for i, tt := range tests {
req, err := NewRequest("POST", "http://localhost/", tt.r)
if req.ContentLength != tt.want {
t.Errorf("test[%d]: ContentLength(%T) = %d; want %d", i, tt.r, req.ContentLength, tt.want)
}
- if (req.ContentLength == 0) != (req.Body == NoBody) {
- t.Errorf("test[%d]: ContentLength = %d but Body non-nil is %v", i, req.ContentLength, req.Body != nil)
- }
}
}
}
}
-func TestNewRequestNoBody(t *testing.T) {
- req, err := NewRequest("GET", "http://foo.com/", NoBody)
- if err != nil {
- t.Fatal(err)
- }
- if req.ContentLength != 0 {
- t.Errorf("ContentLength = %d; want 0", req.ContentLength)
- }
-}
-
func testMissingFile(t *testing.T, req *Request) {
f, fh, err := req.FormFile("missing")
if f != nil {
// inside a NopCloser, and that it serializes it correctly.
func TestRequestWriteClosesBody(t *testing.T) {
rc := &closeChecker{Reader: strings.NewReader("my body")}
- req, _ := NewRequest("POST", "http://foo.com/", rc)
- if req.ContentLength != -1 {
- t.Errorf("got req.ContentLength %d, want -1", req.ContentLength)
+ req, err := NewRequest("POST", "http://foo.com/", rc)
+ if err != nil {
+ t.Fatal(err)
}
buf := new(bytes.Buffer)
- req.Write(buf)
+ if err := req.Write(buf); err != nil {
+ t.Error(err)
+ }
if !rc.closed {
t.Error("body not closed after write")
}