From 2b3be217552ff34d0fcd927698785119763345f3 Mon Sep 17 00:00:00 2001 From: Alex Goodman Date: Tue, 15 Feb 2022 18:56:04 -0500 Subject: [PATCH] empty files should have not mimetype Signed-off-by: Alex Goodman --- pkg/file/mime_type.go | 22 +++++++++++++++++++++- pkg/file/mime_type_test.go | 6 +++++- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/pkg/file/mime_type.go b/pkg/file/mime_type.go index bc308629..797a6fee 100644 --- a/pkg/file/mime_type.go +++ b/pkg/file/mime_type.go @@ -14,11 +14,31 @@ func MIMEType(reader io.Reader) string { if reader == nil { return "" } + + s := sizer{reader: reader} + var mTypeStr string - mType, err := mimetype.DetectReader(reader) + mType, err := mimetype.DetectReader(&s) if err == nil { // extract the string mimetype and ignore aux information (e.g. 'text/plain; charset=utf-8' -> 'text/plain') mTypeStr = strings.Split(mType.String(), ";")[0] } + + // we may have a reader that is not nil but the observed contents was empty + if s.size == 0 { + return "" + } + return mTypeStr } + +type sizer struct { + reader io.Reader + size int64 +} + +func (s *sizer) Read(p []byte) (int, error) { + n, err := s.reader.Read(p) + s.size += int64(n) + return n, err +} diff --git a/pkg/file/mime_type_test.go b/pkg/file/mime_type_test.go index de313abf..48bbbb9c 100644 --- a/pkg/file/mime_type_test.go +++ b/pkg/file/mime_type_test.go @@ -1,7 +1,9 @@ package file import ( + "bytes" "github.com/stretchr/testify/assert" + "io" "os" "testing" ) @@ -30,11 +32,13 @@ func Test_MIMEType(t *testing.T) { } for _, test := range tests { t.Run(test.fixture, func(t *testing.T) { - var f *os.File + var f io.Reader var err error if test.fixture != "" { f, err = os.Open(test.fixture) assert.NoError(t, err) + } else { + f = bytes.NewReader(nil) } assert.Equal(t, test.expected, MIMEType(f)) })