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..d8035a8c 100644 --- a/pkg/file/mime_type_test.go +++ b/pkg/file/mime_type_test.go @@ -2,41 +2,50 @@ package file import ( "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "io" "os" + "strings" "testing" ) func Test_MIMEType(t *testing.T) { + fileReader := func(path string) io.Reader { + f, err := os.Open(path) + require.NoError(t, err) + return f + } + tests := []struct { - fixture string + name string + fixture io.Reader expected string }{ { - // darwin binary - fixture: "test-fixtures/mime/mach-binary", + name: "binary", + fixture: fileReader("test-fixtures/mime/mach-binary"), expected: "application/x-mach-binary", }, { - // script - fixture: "test-fixtures/mime/capture.sh", + name: "script", + fixture: fileReader("test-fixtures/mime/capture.sh"), expected: "text/plain", }, { - // no contents - fixture: "", + name: "no contents", + fixture: strings.NewReader(""), + expected: "", + }, + { + name: "no reader", + fixture: nil, expected: "", }, } for _, test := range tests { - t.Run(test.fixture, func(t *testing.T) { - var f *os.File - var err error - if test.fixture != "" { - f, err = os.Open(test.fixture) - assert.NoError(t, err) - } - assert.Equal(t, test.expected, MIMEType(f)) + t.Run(test.name, func(t *testing.T) { + assert.Equal(t, test.expected, MIMEType(test.fixture)) }) } }