31 lines
565 B
Go
31 lines
565 B
Go
|
|
package helpers
|
||
|
|
|
||
|
|
import (
|
||
|
|
"io"
|
||
|
|
"mime"
|
||
|
|
"net/http"
|
||
|
|
"os"
|
||
|
|
"path/filepath"
|
||
|
|
"strings"
|
||
|
|
)
|
||
|
|
|
||
|
|
func MimeTypeForFile(path string, filename string) string {
|
||
|
|
if mimeType := mime.TypeByExtension(strings.ToLower(filepath.Ext(filename))); mimeType != "" {
|
||
|
|
return mimeType
|
||
|
|
}
|
||
|
|
|
||
|
|
file, err := os.Open(path)
|
||
|
|
if err != nil {
|
||
|
|
return "application/octet-stream"
|
||
|
|
}
|
||
|
|
defer file.Close()
|
||
|
|
|
||
|
|
buffer := make([]byte, 512)
|
||
|
|
bytesRead, err := file.Read(buffer)
|
||
|
|
if err != nil && err != io.EOF {
|
||
|
|
return "application/octet-stream"
|
||
|
|
}
|
||
|
|
|
||
|
|
return http.DetectContentType(buffer[:bytesRead])
|
||
|
|
}
|