blob: 6824ffc2c2604fa964aa00e0e95c4b73962e53d5 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
package internal
import (
"mime"
"os"
"strings"
"unicode/utf8"
)
func MediaType(fpath string) string {
if strings.HasSuffix(fpath, ".gmi") {
// This may not be present in the listings searched by mime.TypeByExtension,
// so provide a dedicated fast path for it here.
return "text/gemini"
}
slashIdx := strings.LastIndex(fpath, "/")
dotIdx := strings.LastIndex(fpath[slashIdx+1:], ".")
if dotIdx == -1 {
return "application/octet-stream"
}
ext := fpath[slashIdx+1+dotIdx:]
mtype := mime.TypeByExtension(ext)
if mtype == "" {
if ContentsAreText(fpath) {
return "text/plain"
}
return "application/octet-stream"
}
return mtype
}
func ContentsAreText(fpath string) bool {
f, err := os.Open(fpath)
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
}
|