Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion render/data.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@

package render

import "net/http"
import (
"net/http"
"strconv"
)

// Data contains ContentType and bytes data.
type Data struct {
Expand All @@ -15,6 +18,9 @@ type Data struct {
// Render (Data) writes data with custom ContentType.
func (r Data) Render(w http.ResponseWriter) (err error) {
r.WriteContentType(w)
if len(r.Data) > 0 {
w.Header().Set("Content-Length", strconv.Itoa(len(r.Data)))
}
Comment on lines +21 to +23
Copy link

Copilot AI May 20, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The condition 'if len(r.Data) > 0' prevents setting the Content-Length header when the data length is 0, causing test failures for zero-length responses. Consider removing the condition so the header is always set to strconv.Itoa(len(r.Data)).

Suggested change
if len(r.Data) > 0 {
w.Header().Set("Content-Length", strconv.Itoa(len(r.Data)))
}
w.Header().Set("Content-Length", strconv.Itoa(len(r.Data)))

Copilot uses AI. Check for mistakes.
_, err = w.Write(r.Data)
return
}
Expand Down
31 changes: 31 additions & 0 deletions render/render_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"encoding/xml"
"errors"
"html/template"
"io"
"net"
"net/http"
"net/http/httptest"
Expand Down Expand Up @@ -420,6 +421,36 @@ func TestRenderData(t *testing.T) {
require.NoError(t, err)
assert.Equal(t, "#!PNG some raw data", w.Body.String())
assert.Equal(t, "image/png", w.Header().Get("Content-Type"))
assert.Equal(t, "19", w.Header().Get("Content-Length"))
}

func TestRenderDataContentLength(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
size, err := strconv.Atoi(r.URL.Query().Get("size"))
assert.NoError(t, err)

data := Data{
ContentType: "application/octet-stream",
Data: make([]byte, size),
}
assert.NoError(t, data.Render(w))
}))
t.Cleanup(srv.Close)

for _, size := range []int{0, 1, 100, 100_000} {
t.Run(strconv.Itoa(size), func(t *testing.T) {
resp, err := http.Get(srv.URL + "?size=" + strconv.Itoa(size))
require.NoError(t, err)
defer resp.Body.Close()

assert.Equal(t, "application/octet-stream", resp.Header.Get("Content-Type"))
assert.EqualValues(t, strconv.Itoa(size), resp.Header.Get("Content-Length"))

actual, err := io.Copy(io.Discard, resp.Body)
require.NoError(t, err)
assert.EqualValues(t, size, actual)
})
}
}

func TestRenderString(t *testing.T) {
Expand Down