diff --git a/pkg/routing/content_types.go b/pkg/routing/content_types.go index ec72284..7b5848f 100644 --- a/pkg/routing/content_types.go +++ b/pkg/routing/content_types.go @@ -4,6 +4,7 @@ package routing import ( "errors" "path/filepath" + "strings" ) // getContentType returns the http header safe content-type attribute for the @@ -13,24 +14,27 @@ import ( // BUG(george-e-shaw-iv) Does not cover the bulk of encountered content types on the web func GetContentType(path string) (string, error) { var contentType string - fileType := filepath.Ext(path) - if fileType == "" { - return contentType, errors.New("Invalid path, contained no period-separated content-type") + path = filepath.Base(path) + ext := filepath.Ext(path) + fn := strings.TrimSuffix(path, ext) + + if ext == "" || fn == "" { + return "", errors.New("Invalid file path") } - switch fileType { - case "html": + switch ext { + case ".html": contentType = "text/html" - case "css": + case ".css": contentType = "text/css" - case "js": + case ".js": contentType = "text/javascript" - case "png": + case ".png": contentType = "image/png" - case "jpg": + case ".jpg": fallthrough - case "jpeg": + case ".jpeg": contentType = "image/jpeg" default: contentType = "text/plain" diff --git a/pkg/routing/content_types_test.go b/pkg/routing/content_types_test.go new file mode 100644 index 0000000..f6cbe8a --- /dev/null +++ b/pkg/routing/content_types_test.go @@ -0,0 +1,36 @@ +package routing + +import ( + "testing" +) + +func TestContentType(t *testing.T) { + cases := []struct { + input string + mime string + ok bool + }{ + {"/path/to/index.html", "text/html", true}, + {"somepath/file.css", "text/css", true}, + {"test.js", "text/javascript", true}, + {"asdf.png", "image/png", true}, + {"asdfpng", "", false}, + {"/something.jpg", "image/jpeg", true}, + {"/something.jpeg", "image/jpeg", true}, + {"this/should/fail/.png", "", false}, + } + + for _, tc := range cases { + mime, err := GetContentType(tc.input) + if err != nil && tc.ok == true { + t.Fatalf("\nGetContentType(%s): Got an error, expected OK.", tc.input) + } + if err == nil && tc.ok == false { + t.Fatalf("\nGetContentType(%s): Expected error, got: %s", tc.input, tc.mime) + } + if mime != tc.mime { + t.Fatalf("\nGetContentType(%s):\nWant: %s\nGot: %s", tc.input, tc.mime, mime) + } + } + +}