Set content type on response for static file serve

master
Bel LaPointe 2020-07-23 23:29:34 -06:00
parent bbdd4919ba
commit ed3006d359
2 changed files with 33 additions and 13 deletions

View File

@ -3,6 +3,7 @@ package view
import ( import (
"local/dndex/config" "local/dndex/config"
"local/dndex/storage" "local/dndex/storage"
"local/simpleserve/simpleserve"
"net/http" "net/http"
"path" "path"
"strings" "strings"
@ -14,6 +15,7 @@ func files(_ storage.Graph, w http.ResponseWriter, r *http.Request) error {
http.NotFound(w, r) http.NotFound(w, r)
return nil return nil
} }
simpleserve.SetContentTypeIfMedia(w, r)
switch r.Method { switch r.Method {
case http.MethodGet: case http.MethodGet:
return filesGet(w, r) return filesGet(w, r)

View File

@ -9,6 +9,7 @@ import (
"net/http/httptest" "net/http/httptest"
"os" "os"
"path" "path"
"strings"
"testing" "testing"
) )
@ -41,20 +42,37 @@ func TestFiles(t *testing.T) {
} }
}) })
t.Run("get text file", func(t *testing.T) { t.Run("get typed files", func(t *testing.T) {
f, err := ioutil.TempFile(d, "*.txt") cases := map[string]string{
t.Logf("tempFile(%q, *.txt) = %q", d, f.Name()) "txt": "text/plain",
if err != nil { "jpeg": "image/jpeg",
t.Fatal(err) "jpg": "image/jpeg",
"gif": "image/gif",
"mkv": "video/x-matroska",
} }
f.Write([]byte("hello, world")) for ext, ct := range cases {
f.Close() for _, extC := range []string{strings.ToLower(ext), strings.ToUpper(ext)} {
r := httptest.NewRequest(http.MethodGet, path.Join(config.New().FilePrefix, path.Base(f.Name())), nil) f, err := ioutil.TempFile(d, "*."+extC)
w := httptest.NewRecorder() t.Logf("tempFile(%q, *.%s) = %q", d, extC, f.Name())
t.Logf("URL = %q", r.URL.String()) if err != nil {
handler.ServeHTTP(w, r) t.Fatal(err)
if w.Code != http.StatusOK { }
t.Fatalf("%d: %s", w.Code, w.Body.Bytes()) f.Write([]byte("hello, world"))
f.Close()
r := httptest.NewRequest(http.MethodGet, path.Join(config.New().FilePrefix, path.Base(f.Name())), nil)
w := httptest.NewRecorder()
t.Logf("URL = %q", r.URL.String())
handler.ServeHTTP(w, r)
if w.Code != http.StatusOK {
t.Fatalf("%d: %s", w.Code, w.Body.Bytes())
}
if contentType, ok := w.Header()["Content-Type"]; !ok {
t.Fatal(w.Header())
} else if len(contentType) < 1 || !strings.HasPrefix(contentType[0], ct) {
t.Fatal(contentType, ", want:", ct)
}
t.Logf("%+v", w)
}
} }
}) })
} }