mirror of
https://github.com/donl/gPanel.git
synced 2026-06-30 06:12:06 -06:00
update content type function with tests
This commit is contained in:
parent
9b189d7d32
commit
e098a7a743
2 changed files with 50 additions and 10 deletions
|
|
@ -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"
|
||||
|
|
|
|||
36
pkg/routing/content_types_test.go
Normal file
36
pkg/routing/content_types_test.go
Normal file
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue