From a29a9dbb98207c8c3312c5d0c0eb53abeb7eec05 Mon Sep 17 00:00:00 2001 From: Djalil Dreamski <32184973+dreamski21@users.noreply.github.com> Date: Wed, 6 Nov 2019 01:52:49 +0100 Subject: [PATCH] gateway: ServeFile: use file extension to determine Content-Type License: MIT Signed-off-by: Abdeldjalil Hebal --- core/corehttp/gateway_handler.go | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/core/corehttp/gateway_handler.go b/core/corehttp/gateway_handler.go index 540b83347..14973b0d7 100644 --- a/core/corehttp/gateway_handler.go +++ b/core/corehttp/gateway_handler.go @@ -11,7 +11,8 @@ import ( "runtime/debug" "strings" "time" - + "mime" + "github.com/dustin/go-humanize" "github.com/ipfs/go-cid" files "github.com/ipfs/go-ipfs-files" @@ -383,15 +384,23 @@ func (i *gatewayHandler) serveFile(w http.ResponseWriter, req *http.Request, nam } } - buf := make([]byte, 512) - _, _ = content.Read(buf) - mime := http.DetectContentType(buf) - - if strings.HasPrefix(mime, "text/html;") { - mime = "text/html" + ctype := mime.TypeByExtension(gopath.Ext(name)) + if ctype == "" { + buf := make([]byte, 512) + n, _ := io.ReadFull(content, buf[:]) + ctype = http.DetectContentType(buf[:n]) + _, err := content.Seek(0, io.SeekStart) + if err != nil { + Error(w, "seeker can't seek", http.StatusInternalServerError) + return + } } - w.Header().Set("Content-Type", mime) + if strings.HasPrefix(ctype, "text/html;") { + ctype = "text/html" + } + w.Header().Set("Content-Type", ctype) + _, _ = content.Seek(0, io.SeekStart) http.ServeContent(w, req, name, modtime, content) }