Switch to mime standard lib for mime-type detection
This commit is contained in:
parent
0cf0ecc5e8
commit
a72ade041b
24
api.go
24
api.go
@ -3,20 +3,15 @@ package main
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"mime"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
var MIME_TYPES = map[string]string{
|
var extraMimeTypes = map[string]string{
|
||||||
".css": "text/css",
|
|
||||||
".js": "application/javascript",
|
|
||||||
".icon": "image-x-icon",
|
".icon": "image-x-icon",
|
||||||
".eot": "application/vnd.ms-fontobject",
|
|
||||||
".svg": "image/svg+xml",
|
|
||||||
".ttf": "application/font-sfnt",
|
|
||||||
".woff": "application/font-woff",
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type Error struct {
|
type Error struct {
|
||||||
@ -28,13 +23,18 @@ func NewError(err error) Error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func assetContentType(name string) string {
|
func assetContentType(name string) string {
|
||||||
mime := MIME_TYPES[filepath.Ext(name)]
|
ext := filepath.Ext(name)
|
||||||
|
result := mime.TypeByExtension(ext)
|
||||||
|
|
||||||
if mime != "" {
|
if result == "" {
|
||||||
return mime
|
result = extraMimeTypes[ext]
|
||||||
} else {
|
|
||||||
return "text/plain"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if result == "" {
|
||||||
|
result = "text/plain; charset=utf-8"
|
||||||
|
}
|
||||||
|
|
||||||
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
func setupRoutes(router *gin.Engine) {
|
func setupRoutes(router *gin.Engine) {
|
||||||
|
29
api_test.go
Normal file
29
api_test.go
Normal file
@ -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))
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user