-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmime.go
88 lines (74 loc) · 1.97 KB
/
mime.go
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package main
import (
"net/http"
"regexp"
"strings"
"github.com/rs/zerolog"
"github.com/chronos-tachyon/roxy/internal/constants"
)
type MimeRule struct {
rx *regexp.Regexp
contentType string
contentLang string
contentEnc string
}
func CompileMimeRule(cfg *MimeRuleConfig) (*MimeRule, error) {
pieces := make([]string, len(cfg.Suffixes))
for i, suffix := range cfg.Suffixes {
pieces[i] = regexp.QuoteMeta(suffix)
}
pattern := `^.*(?:` + strings.Join(pieces, `|`) + `)$`
rx := regexp.MustCompile(pattern)
return &MimeRule{
rx: rx,
contentType: cfg.ContentType,
contentLang: cfg.ContentLang,
contentEnc: cfg.ContentEnc,
}, nil
}
func DetectMimeProperties(impl *Impl, logger zerolog.Logger, filesystem http.FileSystem, path string) (contentType string, contentLang string, contentEnc string) {
contentType = constants.ContentTypeAppOctetStream
contentLang = ""
contentEnc = ""
f, err := filesystem.Open(path)
if err != nil {
logger.Error().Str("file", path).Err(err).Msg("DetectMimeProperties: failed to open file")
return
}
defer func() {
_ = f.Close()
}()
haveContentType := false
if raw, err := readXattr(f, xattrMimeType); err == nil {
contentType = string(raw)
haveContentType = true
}
haveContentLang := false
if raw, err := readXattr(f, xattrMimeLang); err == nil {
contentLang = string(raw)
haveContentLang = true
}
haveContentEnc := false
if raw, err := readXattr(f, xattrMimeEnc); err == nil {
contentEnc = string(raw)
haveContentEnc = true
}
for _, mimeRule := range impl.mimeRules {
if !mimeRule.rx.MatchString(path) {
continue
}
if !haveContentType && mimeRule.contentType != "" {
contentType = mimeRule.contentType
haveContentType = true
}
if !haveContentLang && mimeRule.contentLang != "" {
contentLang = mimeRule.contentLang
haveContentLang = true
}
if !haveContentEnc && mimeRule.contentEnc != "" {
contentEnc = mimeRule.contentEnc
haveContentEnc = true
}
}
return
}