-
Notifications
You must be signed in to change notification settings - Fork 56
/
content.go
54 lines (45 loc) · 1.18 KB
/
content.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
package serverHandler
import (
"mime"
"net/http"
"os"
"path"
"strconv"
"time"
)
func getContentType(item os.FileInfo, file *os.File) (string, error) {
ext := path.Ext(item.Name())
ctype := mime.TypeByExtension(ext)
if len(ctype) > 0 {
return ctype, nil
}
var buf [512]byte
n, err := file.Read(buf[:])
if err != nil {
return ctype, err
}
ctype = http.DetectContentType(buf[:n])
return ctype, nil
}
func (h *handler) content(w http.ResponseWriter, r *http.Request, data *responseData) {
header := w.Header()
if data.IsDownload {
header.Set("Content-Disposition", "attachment; filename*=UTF-8''"+data.ItemName)
}
item := data.Item
file := data.File
if needResponseBody(r.Method) {
http.ServeContent(w, r, item.Name(), item.ModTime(), file)
return
}
ctype, err := getContentType(item, file)
if err == nil {
header.Set("Content-Type", ctype)
header.Set("Content-Length", strconv.FormatInt(item.Size(), 10))
header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
header.Set("Last-Modified", item.ModTime().UTC().Format(http.TimeFormat))
} else if data.Status == http.StatusOK {
data.Status = http.StatusInternalServerError
}
w.WriteHeader(data.Status)
}