Welcome to mirror list, hosted at ThFree Co, Russian Federation.

gitlab.com/gitlab-org/gitlab-pages.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorReto Kaiser <reto@retoonline.com>2019-01-10 12:51:04 +0300
committerReto Kaiser <reto@retoonline.com>2019-01-10 12:51:04 +0300
commit5ad7c5480133c944839a939b1781bfe178c70113 (patch)
tree8acfbe20d35c840ffdecfce3d14fbab1c33a1d2c
parent52e9febadad57fb11e33d5d895408de7ef14f3a6 (diff)
Move content-type detection to separate function D.detectContentType()
-rw-r--r--internal/domain/domain.go31
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)