Skip to content

Commit

Permalink
empty files should have not mimetype
Browse files Browse the repository at this point in the history
Signed-off-by: Alex Goodman <[email protected]>
  • Loading branch information
wagoodman committed Feb 15, 2022
1 parent 25ebd49 commit 2b3be21
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
22 changes: 21 additions & 1 deletion pkg/file/mime_type.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
6 changes: 5 additions & 1 deletion pkg/file/mime_type_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package file

import (
"bytes"
"github.com/stretchr/testify/assert"
"io"
"os"
"testing"
)
Expand Down Expand Up @@ -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))
})
Expand Down

0 comments on commit 2b3be21

Please sign in to comment.