-
Notifications
You must be signed in to change notification settings - Fork 0
/
mime.go
65 lines (53 loc) · 1.47 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
// Path: mime.go
// A simple static HTTP server that supports custom mime-types.
package main
import (
"encoding/json"
"log"
"mime"
"net/http"
"os"
"path/filepath"
)
func addMimeTypes() error {
log.Println("Initializing mime-types ...")
mimeTypes, err := loadMimeTypes(*mimeConfig)
if err != nil {
return err
}
for ext, typ := range mimeTypes {
log.Println("Adding mime-type", typ, "for extension", "."+ext, "...")
if err := mime.AddExtensionType("."+ext, typ); err != nil {
return err
}
}
return nil
}
func serveFile(w http.ResponseWriter, r *http.Request) {
log.Println("Serving file", *dir+r.URL.Path, "with HTTP method", r.Method, "...")
w.Header().Set("Content-Type", mime.TypeByExtension(filepath.Ext(r.URL.Path)))
http.ServeFile(w, r, *dir+r.URL.Path)
}
func loadMimeTypes(path string) (map[string]string, error) {
log.Println("Loading mime-types from", path, "...")
mimeTypesJSONFile, err := os.Open(path)
if err != nil {
return nil, err
}
defer mimeTypesJSONFile.Close()
log.Println("mimeTypesJSONFile:", mimeTypesJSONFile)
var mimeTypes map[string][]string
if err := json.NewDecoder(mimeTypesJSONFile).Decode(&mimeTypes); err != nil {
return nil, err
}
log.Println("mimeTypes:", mimeTypes)
// Convert the mime-types to a map.
mimeTypesMap := make(map[string]string)
for typ, exts := range mimeTypes {
for _, ext := range exts {
mimeTypesMap[ext] = typ
}
}
log.Println("mimeTypesMap:", mimeTypesMap)
return mimeTypesMap, nil
}