From 0386be537b3e0e8097e30b0792589ad8b6819cba Mon Sep 17 00:00:00 2001 From: tjpcc Date: Mon, 9 Oct 2023 08:55:10 -0600 Subject: improves filetype detection --- contrib/fs/file.go | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) (limited to 'contrib/fs/file.go') diff --git a/contrib/fs/file.go b/contrib/fs/file.go index 7690a62..9f11f4f 100644 --- a/contrib/fs/file.go +++ b/contrib/fs/file.go @@ -2,7 +2,9 @@ package fs import ( "mime" + "os" "strings" + "unicode/utf8" ) func mediaType(filePath string) string { @@ -21,6 +23,9 @@ func mediaType(filePath string) string { mtype := mime.TypeByExtension(ext) if mtype == "" { + if contentsAreText(filePath) { + return "text/plain" + } return "application/octet-stream" } return mtype @@ -34,3 +39,28 @@ func isPrivate(fullpath string) bool { } return false } + +func contentsAreText(filepath string) bool { + f, err := os.Open(filepath) + if err != nil { + return false + } + defer func() { _ = f.Close() }() + + var buf [1024]byte + n, err := f.Read(buf[:]) + if err != nil { + return false + } + + for i, c := range string(buf[:n]) { + if i+utf8.UTFMax > n { + // incomplete last char + break + } + if c == 0xFFFD || c < ' ' && c != '\n' && c != '\t' && c != '\f' { + return false + } + } + return true +} -- cgit v1.2.3