Skip to content
Myr

fix(render): write content length in Data.Render (#4206)

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

* init test * fix test * fix assert.EqualValues usage ---------

authored by Denis Galeev · committed by GitHub · parent db30908 · Browse files · 2 files+38 added−1 removed
This commit

State

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

Trailers

  • Co-authored-by: Bo-Yi Wu <appleboy.tw@gmail.com>

Diff stats

2 files+38 added−1 removed

  • other:+38 added−1 removed

2 files+38 added−1 removed

modified:render/data.go+7 added-1 removed
2 unmodified lines
3// license that can be found in the LICENSE file.45package render67import "net/http"7import (8 "net/http"9 "strconv"10)1112// Data contains ContentType and bytes data.13type Data struct {14 ContentType string
2 unmodified lines
1718// Render (Data) writes data with custom ContentType.19func (r Data) Render(w http.ResponseWriter) (err error) {20 r.WriteContentType(w)21 if len(r.Data) > 0 {22 w.Header().Set("Content-Length", strconv.Itoa(len(r.Data)))23 }24 _, err = w.Write(r.Data)25 return26}27
4 unmodified lines
modified:render/render_test.go+31 added
6 unmodified lines
7import (8 "encoding/xml"9 "errors"10 "html/template"11 "io"12 "net"13 "net/http"14 "net/http/httptest"15 "strconv"
437 unmodified lines
453454 require.NoError(t, err)455 assert.Equal(t, "#!PNG some raw data", w.Body.String())456 assert.Equal(t, "image/png", w.Header().Get("Content-Type"))457 assert.Equal(t, "19", w.Header().Get("Content-Length"))458}459460func TestRenderDataContentLength(t *testing.T) {461 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {462 size, err := strconv.Atoi(r.URL.Query().Get("size"))463 assert.NoError(t, err)464465 data := Data{466 ContentType: "application/octet-stream",467 Data: make([]byte, size),468 }469 assert.NoError(t, data.Render(w))470 }))471 t.Cleanup(srv.Close)472473 for _, size := range []int{0, 1, 100, 100_000} {474 t.Run(strconv.Itoa(size), func(t *testing.T) {475 resp, err := http.Get(srv.URL + "?size=" + strconv.Itoa(size))476 require.NoError(t, err)477 defer resp.Body.Close()478479 assert.Equal(t, "application/octet-stream", resp.Header.Get("Content-Type"))480 assert.Equal(t, strconv.Itoa(size), resp.Header.Get("Content-Length"))481482 actual, err := io.Copy(io.Discard, resp.Body)483 require.NoError(t, err)484 assert.EqualValues(t, size, actual)485 })486 }487}488489func TestRenderString(t *testing.T) {490 w := httptest.NewRecorder()491492 (String{
193 unmodified lines