summaryrefslogtreecommitdiff
path: root/gopher
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 /gopher
parent775c0c1040e6a6622fec39d49b354bfa194a6998 (diff)
improves filetype detection
Diffstat (limited to 'gopher')
-rw-r--r--gopher/response.go33
1 files changed, 32 insertions, 1 deletions
diff --git a/gopher/response.go b/gopher/response.go
index c594fa7..269176f 100644
--- a/gopher/response.go
+++ b/gopher/response.go
@@ -5,9 +5,11 @@ import (
"fmt"
"io"
"mime"
+ "os"
"path"
"strings"
"sync"
+ "unicode/utf8"
"tildegit.org/tjp/sliderule/internal/types"
)
@@ -173,7 +175,7 @@ func GuessItemType(filepath string) types.Status {
case ".txt", ".gmi", ".md":
return TextFileType
case ".gif":
- return GifFileType
+ return GifFileType
case ".png":
return PngImageFileType
case ".jpg", ".jpeg", ".tif", ".tiff":
@@ -205,5 +207,34 @@ func GuessItemType(filepath string) types.Status {
return TextFileType
}
+ if contentsAreText(filepath) {
+ return TextFileType
+ }
+
return BinaryFileType
}
+
+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
+}