Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FIX] allow empty headers on DataFromReader #2121

Merged
merged 2 commits into from
Nov 25, 2019
Merged
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
17 changes: 17 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1799,6 +1799,23 @@ func TestContextRenderDataFromReader(t *testing.T) {
assert.Equal(t, extraHeaders["Content-Disposition"], w.Header().Get("Content-Disposition"))
}

func TestContextRenderDataFromReaderNoHeaders(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)

body := "#!PNG some raw data"
reader := strings.NewReader(body)
contentLength := int64(len(body))
contentType := "image/png"

c.DataFromReader(http.StatusOK, contentLength, contentType, reader, nil)

assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, body, w.Body.String())
assert.Equal(t, contentType, w.Header().Get("Content-Type"))
assert.Equal(t, fmt.Sprintf("%d", contentLength), w.Header().Get("Content-Length"))
}

type TestResponseRecorder struct {
*httptest.ResponseRecorder
closeChannel chan bool
Expand Down
3 changes: 3 additions & 0 deletions render/reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ type Reader struct {
func (r Reader) Render(w http.ResponseWriter) (err error) {
r.WriteContentType(w)
if r.ContentLength >= 0 {
if r.Headers == nil {
r.Headers = map[string]string{}
}
r.Headers["Content-Length"] = strconv.FormatInt(r.ContentLength, 10)
}
r.writeHeaders(w, r.Headers)
Expand Down
23 changes: 23 additions & 0 deletions render/reader_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// 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)
}