Skip to content

Commit

Permalink
refactor: use http.DetectContentType() at end
Browse files Browse the repository at this point in the history
  • Loading branch information
aofei committed Dec 21, 2018
1 parent ef76bff commit af57ebf
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 11 deletions.
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,11 @@
A MIME type sniffer for Go.

MIMESniffer implements the algorithm described at
[here](https://mimesniff.spec.whatwg.org) to determine the MIME type of the
given data. So it can be used as a substitute for `http.DetectContentType()`.
[here](https://mimesniff.spec.whatwg.org) and uses the file signatures (aka
[magic numbers](https://en.wikipedia.org/wiki/Magic_number_\(programming\)#Magic_numbers_in_files))
listed [here](https://www.garykessler.net/library/file_sigs.html) to determine
the MIME type of the given data. So it can be used as an alternative for the
`http.DetectContentType()`.

## Features

Expand Down
10 changes: 2 additions & 8 deletions mimesniffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,8 @@ func Register(mimeType string, sniffer func([]byte) bool) {
// It always returns a valid MIME type: if it cannot determine a more specific
// one, it returns "application/octet-stream".
func Sniff(b []byte) string {
const unknownType = "application/octet-stream"

if len(b) == 0 {
return unknownType
return "application/octet-stream"
}

for mt, s := range registeredSniffers {
Expand All @@ -90,17 +88,13 @@ func Sniff(b []byte) string {
}
}

if mt := http.DetectContentType(b); mt != unknownType {
return mt
}

for mt, s := range defaultSniffers {
if s(b) {
return mt
}
}

return unknownType
return http.DetectContentType(b)
}

// applicationEPUBZip reports whether the b's MIME type is
Expand Down
3 changes: 2 additions & 1 deletion mimesniffer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ func TestSniff(t *testing.T) {
})

assert.Equal(t, Sniff([]byte{0x00}), "foo/bar")
assert.Equal(t, Sniff([]byte("foobar")), "text/plain; charset=utf-8")
assert.Equal(t, Sniff([]byte{0x01}), "application/octet-stream")
assert.Equal(t, Sniff([]byte{0xff, 0xf1}), "audio/aac")
assert.Equal(t, Sniff([]byte("foobar")), "text/plain; charset=utf-8")
}

0 comments on commit af57ebf

Please sign in to comment.