From ea3554912c873c8e91908dffe441cb9da02045ad Mon Sep 17 00:00:00 2001 From: Bel LaPointe Date: Thu, 23 Jul 2020 23:23:26 -0600 Subject: [PATCH] Export helper --- main.go | 59 ++-------------------------------------------------- main_test.go | 3 ++- 2 files changed, 4 insertions(+), 58 deletions(-) diff --git a/main.go b/main.go index a4145cc..a49d166 100755 --- a/main.go +++ b/main.go @@ -15,6 +15,7 @@ import ( "io" "local/args" "local/gziphttp" + "local/simpleserve/simpleserve" "log" "net/http" "net/http/httptest" @@ -99,7 +100,7 @@ func endpoints(foo http.HandlerFunc) http.HandlerFunc { fmt.Fprintln(w, err.Error()) } } else { - setContentTypeIfMedia(w, r) + simpleserve.SetContentTypeIfMedia(w, r) foo(w, r) } } @@ -202,59 +203,3 @@ func toRealPath(p string) string { d := path.Join(fs.Get("d").GetString()) return path.Join(d, p) } - -func setContentTypeIfMedia(w http.ResponseWriter, r *http.Request) { - ext := strings.ToLower(path.Ext(r.URL.Path)) - if i := strings.LastIndex(ext, "."); i != -1 { - ext = ext[i:] - } - 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) -} diff --git a/main_test.go b/main_test.go index 8f1ae58..bbc6bee 100644 --- a/main_test.go +++ b/main_test.go @@ -1,6 +1,7 @@ package main import ( + "local/simpleserve/simpleserve" "net/http" "net/http/httptest" "net/url" @@ -25,7 +26,7 @@ func TestSetContentType(t *testing.T) { t.Run(name, func(t *testing.T) { r := &http.Request{URL: &url.URL{Path: c.path}} w := httptest.NewRecorder() - setContentTypeIfMedia(w, r) + simpleserve.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) }