4 Commits
v0.6 ... v0.9

Author SHA1 Message Date
Bel LaPointe
c4747039a0 Fix pdf 2020-07-12 17:56:37 -06:00
bel
3c5f23d3ac add a unit test 2020-05-29 18:12:18 -06:00
bel
c6109e23af More types 2020-04-13 20:47:42 +00:00
bel
6ae09962ad More content types 2020-04-13 13:00:30 +00:00
2 changed files with 86 additions and 11 deletions

63
main.go
View File

@@ -204,16 +204,57 @@ func toRealPath(p string) string {
} }
func setContentTypeIfMedia(w http.ResponseWriter, r *http.Request) { func setContentTypeIfMedia(w http.ResponseWriter, r *http.Request) {
switch path.Ext(r.URL.Path) { ext := strings.ToLower(path.Ext(r.URL.Path))
case ".mp4": if i := strings.LastIndex(ext, "."); i != -1 {
w.Header().Set("Content-Type", "video/mp4") ext = ext[i:]
case ".webm":
w.Header().Set("Content-Type", "video/webm")
case ".mkv":
w.Header().Set("Content-Type", "video/x-matroska")
case ".mp3":
w.Header().Set("Content-Type", "audio/mpeg3")
case ".epub", ".mobi":
w.Header().Set("Content-Disposition", "attachment")
} }
k := "Content-Type"
v := ""
switch ext {
case ".mp4":
v = "video/mp4"
case ".mkv":
v = "video/x-matroska"
case ".mp3":
v = "audio/mpeg3"
case ".epub", ".mobi":
k = "Content-Disposition"
v = "attachment"
case ".jpg", ".jpeg":
v = "image/jpeg"
case ".gif":
v = "image/gif"
case ".png":
v = "image/png"
case ".ico":
v = "image/x-icon"
case ".svg":
v = "image/svg+xml"
case ".css":
v = "text/css"
case ".js":
v = "text/javascript"
case ".json":
v = "application/json"
case ".html", ".htm":
v = "text/html"
case ".pdf":
w.Header().Set("Content-Disposition", fmt.Sprintf("inline; filename=%q", path.Base(r.URL.Path)))
v = "application/pdf"
case ".webm":
v = "video/webm"
case ".weba":
v = "audio/webm"
case ".webp":
v = "image/webp"
case ".zip":
v = "application/zip"
case ".7z":
v = "application/x-7z-compressed"
case ".tar":
v = "application/x-tar"
default:
return
}
w.Header().Set(k, v)
} }

34
main_test.go Normal file
View File

@@ -0,0 +1,34 @@
package main
import (
"net/http"
"net/http/httptest"
"net/url"
"testing"
)
func TestSetContentType(t *testing.T) {
t.Parallel()
cases := map[string]struct {
path string
want string
}{
"css with multi .": {
path: "/static/css/main.2145ce41.chunk.css",
want: "text/css",
},
}
for name, d := range cases {
c := d
t.Run(name, func(t *testing.T) {
r := &http.Request{URL: &url.URL{Path: c.path}}
w := httptest.NewRecorder()
setContentTypeIfMedia(w, r)
if ct := w.Header().Get("Content-Type"); ct != c.want {
t.Errorf("wrong content type: want %q, got %q", c.want, ct)
}
})
}
}