Skip to content
Myr

Support negative Content-Length in DataFromReader (#1981)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

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.

authored by Segev Finer · committed by thinkerou · parent 461df93 · Browse files · 2 files+26 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+26 added−1 removed

  • other:+26 added−1 removed

2 files+26 added−1 removed

modified:render/reader.go+3 added-1 removed
19 unmodified lines
2021// Render (Reader) writes data with custom ContentType and headers.22func (r Reader) Render(w http.ResponseWriter) (err error) {23 r.WriteContentType(w)24 if r.ContentLength >= 0 {24 r.Headers["Content-Length"] = strconv.FormatInt(r.ContentLength, 10)25 r.Headers["Content-Length"] = strconv.FormatInt(r.ContentLength, 10)26 }27 r.writeHeaders(w, r.Headers)28 _, err = io.Copy(w, r.Reader)29 return30}
15 unmodified lines
modified:render/render_test.go+23 added
496 unmodified lines
497 assert.Equal(t, strconv.Itoa(len(body)), w.Header().Get("Content-Length"))498 assert.Equal(t, headers["Content-Disposition"], w.Header().Get("Content-Disposition"))499 assert.Equal(t, headers["x-request-id"], w.Header().Get("x-request-id"))500}501502func TestRenderReaderNoContentLength(t *testing.T) {503 w := httptest.NewRecorder()504505 body := "#!PNG some raw data"506 headers := make(map[string]string)507 headers["Content-Disposition"] = `attachment; filename="filename.png"`508 headers["x-request-id"] = "requestId"509510 err := (Reader{511 ContentLength: -1,512 ContentType: "image/png",513 Reader: strings.NewReader(body),514 Headers: headers,515 }).Render(w)516517 assert.NoError(t, err)518 assert.Equal(t, body, w.Body.String())519 assert.Equal(t, "image/png", w.Header().Get("Content-Type"))520 assert.NotContains(t, "Content-Length", w.Header())521 assert.Equal(t, headers["Content-Disposition"], w.Header().Get("Content-Disposition"))522 assert.Equal(t, headers["x-request-id"], w.Header().Get("x-request-id"))523}