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

View File

@ -9,6 +9,7 @@ import (
"net/http/httptest"
"os"
"path"
"strings"
"testing"
)
@ -41,20 +42,37 @@ func TestFiles(t *testing.T) {
}
})
t.Run("get text file", func(t *testing.T) {
f, err := ioutil.TempFile(d, "*.txt")
t.Logf("tempFile(%q, *.txt) = %q", d, f.Name())
if err != nil {
t.Fatal(err)
t.Run("get typed files", func(t *testing.T) {
cases := map[string]string{
"txt": "text/plain",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"gif": "image/gif",
"mkv": "video/x-matroska",
}
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())
for ext, ct := range cases {
for _, extC := range []string{strings.ToLower(ext), strings.ToUpper(ext)} {
f, err := ioutil.TempFile(d, "*."+extC)
t.Logf("tempFile(%q, *.%s) = %q", d, extC, f.Name())
if err != nil {
t.Fatal(err)
}
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)
}
}
})
}