diff options
author | Reto Kaiser <reto@retoonline.com> | 2019-01-10 12:51:04 +0300 |
---|---|---|
committer | Reto Kaiser <reto@retoonline.com> | 2019-01-10 12:51:04 +0300 |
commit | 5ad7c5480133c944839a939b1781bfe178c70113 (patch) | |
tree | 8acfbe20d35c840ffdecfce3d14fbab1c33a1d2c /internal/domain | |
parent | 52e9febadad57fb11e33d5d895408de7ef14f3a6 (diff) |
Move content-type detection to separate function D.detectContentType()
Diffstat (limited to 'internal/domain')
-rw-r--r-- | internal/domain/domain.go | 31 |
1 files changed, 22 insertions, 9 deletions
diff --git a/internal/domain/domain.go b/internal/domain/domain.go index 11c1a56d..80baf259 100644 --- a/internal/domain/domain.go +++ b/internal/domain/domain.go @@ -228,6 +228,25 @@ func (d *D) HasProject(r *http.Request) bool { return false } +// Detect file's content-type either by extension or mime-sniffing. +// Implementation is adapted from Golang's `http.serveContent()` +// See https://github.com/golang/go/blob/902fc114272978a40d2e65c2510a18e870077559/src/net/http/fs.go#L194 +func (d *D) detectContentType(path string) (string, error) { + contentType := mime.TypeByExtension(filepath.Ext(path)) + if contentType == "" { + var buf [512]byte + file, err := os.Open(path) + if err != nil { + return "", err + } + // Using `io.ReadFull()` because `file.Read()` may be chunked. + // Ignoring errors because we don't care if the 512 bytes cannot be read. + n, _ := io.ReadFull(file, buf[:]) + contentType = http.DetectContentType(buf[:n]) + } + return contentType, nil +} + func (d *D) serveFile(w http.ResponseWriter, r *http.Request, origPath string) error { fullPath := handleGZip(w, r, origPath) @@ -248,15 +267,9 @@ func (d *D) serveFile(w http.ResponseWriter, r *http.Request, origPath string) e w.Header().Set("Expires", time.Now().Add(10*time.Minute).Format(time.RFC1123)) } - contentType := mime.TypeByExtension(filepath.Ext(origPath)) - if contentType == "" { - var buf [512]byte - file, err := os.Open(origPath) - if err != nil { - return err - } - n, _ := io.ReadFull(file, buf[:]) - contentType = http.DetectContentType(buf[:n]) + contentType, err := d.detectContentType(origPath) + if err != nil { + return err } w.Header().Set("Content-Type", contentType) |