9e37c86b67
Signed-off-by: Michael Mayer <michael@liquidbytes.net>
40 lines
845 B
Go
40 lines
845 B
Go
package fs
|
|
|
|
import (
|
|
"os"
|
|
|
|
"github.com/h2non/filetype"
|
|
)
|
|
|
|
const (
|
|
MimeTypeJpeg = "image/jpeg"
|
|
MimeTypePng = "image/png"
|
|
MimeTypeGif = "image/gif"
|
|
MimeTypeBitmap = "image/bmp"
|
|
MimeTypeTiff = "image/tiff"
|
|
MimeTypeHEIF = "image/heif"
|
|
)
|
|
|
|
// MimeType returns the mime type of a file, empty string if unknown.
|
|
func MimeType(filename string) string {
|
|
handle, err := os.Open(filename)
|
|
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
|
|
defer handle.Close()
|
|
|
|
// Only the first 261 bytes are used to sniff the content type.
|
|
buffer := make([]byte, 261)
|
|
|
|
if _, err := handle.Read(buffer); err != nil {
|
|
return ""
|
|
} else if t, err := filetype.Get(buffer); err == nil && t != filetype.Unknown {
|
|
return t.MIME.Value
|
|
} else if t := filetype.GetType(NormalizedExt(filename)); t != filetype.Unknown {
|
|
return t.MIME.Value
|
|
} else {
|
|
return ""
|
|
}
|
|
}
|