diff --git a/api.go b/api.go index 3f08a16..fd36e62 100644 --- a/api.go +++ b/api.go @@ -3,20 +3,15 @@ package main import ( "errors" "fmt" + "mime" "path/filepath" "strings" "github.com/gin-gonic/gin" ) -var MIME_TYPES = map[string]string{ - ".css": "text/css", - ".js": "application/javascript", +var extraMimeTypes = map[string]string{ ".icon": "image-x-icon", - ".eot": "application/vnd.ms-fontobject", - ".svg": "image/svg+xml", - ".ttf": "application/font-sfnt", - ".woff": "application/font-woff", } type Error struct { @@ -28,13 +23,18 @@ func NewError(err error) Error { } func assetContentType(name string) string { - mime := MIME_TYPES[filepath.Ext(name)] + ext := filepath.Ext(name) + result := mime.TypeByExtension(ext) - if mime != "" { - return mime - } else { - return "text/plain" + if result == "" { + result = extraMimeTypes[ext] } + + if result == "" { + result = "text/plain; charset=utf-8" + } + + return result } func setupRoutes(router *gin.Engine) { diff --git a/api_test.go b/api_test.go new file mode 100644 index 0000000..d7b58a8 --- /dev/null +++ b/api_test.go @@ -0,0 +1,29 @@ +package main + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_assetContentType(t *testing.T) { + samples := map[string]string{ + "foo.html": "text/html; charset=utf-8", + "foo.css": "text/css; charset=utf-8", + "foo.js": "application/javascript", + "foo.icon": "image-x-icon", + "foo.png": "image/png", + "foo.jpg": "image/jpeg", + "foo.gif": "image/gif", + "foo.eot": "application/vnd.ms-fontobject", + "foo.svg": "image/svg+xml", + "foo.ttf": "application/x-font-ttf", + "foo.woff": "application/x-font-woff", + "foo.foo": "text/plain; charset=utf-8", + "foo": "text/plain; charset=utf-8", + } + + for name, expected := range samples { + assert.Equal(t, expected, assetContentType(name)) + } +}