2020-01-12 14:00:56 +01:00
|
|
|
package fs
|
2019-12-15 17:19:16 +01:00
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
2020-07-21 14:43:45 +02:00
|
|
|
|
|
|
|
"github.com/h2non/filetype"
|
2019-12-15 17:19:16 +01:00
|
|
|
)
|
|
|
|
|
2020-04-07 10:42:42 +02:00
|
|
|
const (
|
2020-07-19 16:39:43 +02:00
|
|
|
MimeTypeJpeg = "image/jpeg"
|
|
|
|
MimeTypePng = "image/png"
|
|
|
|
MimeTypeGif = "image/gif"
|
|
|
|
MimeTypeBitmap = "image/bmp"
|
2020-07-21 14:43:45 +02:00
|
|
|
MimeTypeTiff = "image/tiff"
|
|
|
|
MimeTypeHEIF = "image/heif"
|
2020-04-07 10:42:42 +02:00
|
|
|
)
|
|
|
|
|
2020-01-12 14:00:56 +01:00
|
|
|
// MimeType returns the mime type of a file, empty string if unknown.
|
2019-12-15 17:19:16 +01:00
|
|
|
func MimeType(filename string) string {
|
|
|
|
handle, err := os.Open(filename)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
defer handle.Close()
|
|
|
|
|
2020-07-21 14:43:45 +02:00
|
|
|
// Only the first 261 bytes are used to sniff the content type.
|
|
|
|
buffer := make([]byte, 261)
|
2019-12-15 17:19:16 +01:00
|
|
|
|
2020-07-21 14:43:45 +02:00
|
|
|
if _, err := handle.Read(buffer); err != nil {
|
2019-12-15 17:19:16 +01:00
|
|
|
return ""
|
2020-07-21 14:43:45 +02:00
|
|
|
} else if t, err := filetype.Get(buffer); err != nil {
|
|
|
|
return ""
|
|
|
|
} else {
|
|
|
|
return t.MIME.Value
|
2019-12-15 17:19:16 +01:00
|
|
|
}
|
|
|
|
}
|