summaryrefslogtreecommitdiff
path: root/contrib
diff options
context:
space:
mode:
authortjpcc <tjp@ctrl-c.club>2023-10-09 08:55:10 -0600
committertjpcc <tjp@ctrl-c.club>2023-10-09 08:55:10 -0600
commit0386be537b3e0e8097e30b0792589ad8b6819cba (patch)
tree5d1d9259bb02b942b7b4a6d3da58de3f5f2d90f0 /contrib
parent775c0c1040e6a6622fec39d49b354bfa194a6998 (diff)
improves filetype detection
Diffstat (limited to 'contrib')
-rw-r--r--contrib/fs/file.go30
-rw-r--r--contrib/fs/gopher.go3
2 files changed, 32 insertions, 1 deletions
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
+}
diff --git a/contrib/fs/gopher.go b/contrib/fs/gopher.go
index db21227..0a0b482 100644
--- a/contrib/fs/gopher.go
+++ b/contrib/fs/gopher.go
@@ -185,7 +185,8 @@ func isFile(path string) (bool, error) {
}
func isMap(path string, settings gophermap.FileSystemSettings) bool {
- if strings.HasSuffix(path, ".gophermap") {
+ base := filepath.Base(path)
+ if base == "gophermap" || strings.HasSuffix(base, ".gph") || strings.HasSuffix(base, ".gophermap") {
return true
}
return slices.Contains(settings.DirMaps, filepath.Base(path))