]> Sergey Matveev's repositories - godlighty.git/blob - rc/mime.go
Built-in MIMEs compression capability
[godlighty.git] / rc / mime.go
1 package rc
2
3 import (
4         "embed"
5         _ "embed"
6         "path"
7         "strings"
8
9         "go.stargrave.org/godlighty"
10 )
11
12 const MIMEDir = "mime"
13
14 var (
15         //go:embed mime
16         mimes embed.FS
17 )
18
19 type MIMEEntry struct {
20         ext          string
21         mediaType    string
22         compressible bool
23 }
24
25 func parseMIME(p string) []MIMEEntry {
26         tsv, err := mimes.ReadFile(path.Join(MIMEDir, p))
27         if err != nil {
28                 panic(err)
29         }
30         entries := make([]MIMEEntry, 0)
31         for _, line := range strings.Split(string(tsv), "\n") {
32                 if len(line) == 0 || line[0] == '#' {
33                         continue
34                 }
35                 cols := strings.Split(line, "\t")
36                 entry := MIMEEntry{ext: cols[0], mediaType: cols[1]}
37                 if len(cols) > 2 && cols[2] == "c" {
38                         entry.compressible = true
39                 }
40                 entries = append(entries, entry)
41         }
42         return entries
43 }
44
45 func init() {
46         entries, err := mimes.ReadDir(MIMEDir)
47         if err != nil {
48                 panic(err)
49         }
50         for _, entry := range entries {
51                 bundle := entry.Name()
52                 for _, e := range parseMIME(bundle) {
53                         godlighty.ContentTypes[e.ext] = e.mediaType
54                         if e.compressible {
55                                 godlighty.CompressibleContentTypes[e.mediaType] = struct{}{}
56                         }
57                 }
58         }
59 }