package assets import ( "bytes" "fmt" "net/http" "path" "strings" ) // Known types by extension. The extension wins; sniffing only fills gaps. var mimeByExt = map[string]string{ ".html": "text/html; charset=utf-8", ".htm": "text/html; charset=utf-8", ".css": "text/css; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8", ".json": "application/json", ".txt": "text/plain; charset=utf-8", ".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp", ".ico": "image/x-icon", ".ttf": "font/ttf", ".otf": "font/otf", ".woff": "font/woff", ".woff2": "font/woff2", ".wasm": "application/wasm", } // strict extensions must never resolve to a generic type, and binary ones are // checked against their magic bytes. var wasmMagic = []byte{0x00, 'a', 's', 'm'} // DetectMIME returns the MIME type for name/data. func DetectMIME(name string, data []byte) (string, error) { ext := strings.ToLower(path.Ext(name)) if m, ok := mimeByExt[ext]; ok { if ext == ".wasm" && !bytes.HasPrefix(data, wasmMagic) { return "", fmt.Errorf("%s: .wasm without WebAssembly magic bytes", name) } return m, nil } return http.DetectContentType(data), nil } // BaseMIME strips parameters ("text/css; charset=utf-8" -> "text/css"). func BaseMIME(m string) string { if i := strings.IndexByte(m, ';'); i >= 0 { m = m[:i] } return strings.TrimSpace(m) }