gin/render/reader_test.go
Dhruv P. 50453fd62e fix(render): don't modify caller's headers map in Reader.Render
Reader.Render wrote Content-Length into the caller-supplied Headers map, so DataFromReader leaked a stale Content-Length into later responses that reused the map and raced when the map was shared across requests. Set Content-Length on the response headers instead.
2026-10-20 12:54:36 -04:00

51 lines
1.4 KiB
Go

// Copyright 2019 Gin Core Team. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package render
import (
"net/http/httptest"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestReaderRenderNoHeaders(t *testing.T) {
content := "test"
r := Reader{
ContentLength: int64(len(content)),
Reader: strings.NewReader(content),
}
err := r.Render(httptest.NewRecorder())
require.NoError(t, err)
}
func TestReaderRenderDoesNotModifyHeaders(t *testing.T) {
headers := map[string]string{"Cache-Control": "public"}
w := httptest.NewRecorder()
r := Reader{
ContentLength: 5,
Reader: strings.NewReader("hello"),
Headers: headers,
}
require.NoError(t, r.Render(w))
require.Equal(t, map[string]string{"Cache-Control": "public"}, headers)
require.Equal(t, "5", w.Header().Get("Content-Length"))
// Reusing the same map for a response of unknown length must not
// carry over the Content-Length of the previous response.
w = httptest.NewRecorder()
r = Reader{
ContentLength: -1,
Reader: strings.NewReader("hello, world!"),
Headers: headers,
}
require.NoError(t, r.Render(w))
require.Empty(t, w.Header().Get("Content-Length"))
require.Equal(t, "public", w.Header().Get("Cache-Control"))
require.Equal(t, "hello, world!", w.Body.String())
}