forked from mirror/gin
Support negative Content-Length in DataFromReader (#1981)
You can get an http.Response with ContentLength set to -1 (Chunked encoding), so for DataFromReader to be useful for those we need to support that.
This commit is contained in:
parent
461df9320a
commit
20440b96b9
|
@ -21,7 +21,9 @@ type Reader struct {
|
|||
// Render (Reader) writes data with custom ContentType and headers.
|
||||
func (r Reader) Render(w http.ResponseWriter) (err error) {
|
||||
r.WriteContentType(w)
|
||||
r.Headers["Content-Length"] = strconv.FormatInt(r.ContentLength, 10)
|
||||
if r.ContentLength >= 0 {
|
||||
r.Headers["Content-Length"] = strconv.FormatInt(r.ContentLength, 10)
|
||||
}
|
||||
r.writeHeaders(w, r.Headers)
|
||||
_, err = io.Copy(w, r.Reader)
|
||||
return
|
||||
|
|
|
@ -498,3 +498,26 @@ func TestRenderReader(t *testing.T) {
|
|||
assert.Equal(t, headers["Content-Disposition"], w.Header().Get("Content-Disposition"))
|
||||
assert.Equal(t, headers["x-request-id"], w.Header().Get("x-request-id"))
|
||||
}
|
||||
|
||||
func TestRenderReaderNoContentLength(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
body := "#!PNG some raw data"
|
||||
headers := make(map[string]string)
|
||||
headers["Content-Disposition"] = `attachment; filename="filename.png"`
|
||||
headers["x-request-id"] = "requestId"
|
||||
|
||||
err := (Reader{
|
||||
ContentLength: -1,
|
||||
ContentType: "image/png",
|
||||
Reader: strings.NewReader(body),
|
||||
Headers: headers,
|
||||
}).Render(w)
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, body, w.Body.String())
|
||||
assert.Equal(t, "image/png", w.Header().Get("Content-Type"))
|
||||
assert.NotContains(t, "Content-Length", w.Header())
|
||||
assert.Equal(t, headers["Content-Disposition"], w.Header().Get("Content-Disposition"))
|
||||
assert.Equal(t, headers["x-request-id"], w.Header().Get("x-request-id"))
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue