| 1 | // Copyright (c) 2022 Sumner Evans |
| 2 | // |
| 3 | // This Source Code Form is subject to the terms of the Mozilla Public |
| 4 | // License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 6 | |
| 7 | package util |
| 8 | |
| 9 | import ( |
| 10 | "mime" |
| 11 | "strings" |
| 12 | ) |
| 13 | |
| 14 | // MimeExtensionSanityOverrides includes extensions for various common mimetypes. |
| 15 | // |
| 16 | // This is necessary because sometimes the OS mimetype database and Go interact in weird ways, |
| 17 | // which causes very obscure extensions to be first in the array for common mimetypes |
| 18 | // (e.g. image/jpeg -> .jpe, text/plain -> ,v). |
| 19 | var MimeExtensionSanityOverrides = map[string]string{ |
| 20 | "image/png": ".png", |
| 21 | "image/webp": ".webp", |
| 22 | "image/jpeg": ".jpg", |
| 23 | "image/tiff": ".tiff", |
| 24 | "image/heif": ".heic", |
| 25 | "image/heic": ".heic", |
| 26 | |
| 27 | "audio/mpeg": ".mp3", |
| 28 | "audio/ogg": ".ogg", |
| 29 | "audio/webm": ".webm", |
| 30 | "audio/x-caf": ".caf", |
| 31 | "video/mp4": ".mp4", |
| 32 | "video/mpeg": ".mpeg", |
| 33 | "video/webm": ".webm", |
| 34 | |
| 35 | "text/plain": ".txt", |
| 36 | "text/html": ".html", |
| 37 | |
| 38 | "application/xml": ".xml", |
| 39 | } |
| 40 | |
| 41 | func ExtensionFromMimetype(mimetype string) string { |
| 42 | ext, ok := MimeExtensionSanityOverrides[strings.Split(mimetype, ";")[0]] |
| 43 | if !ok { |
| 44 | exts, _ := mime.ExtensionsByType(mimetype) |
| 45 | if len(exts) > 0 { |
| 46 | ext = exts[0] |
| 47 | } |
| 48 | } |
| 49 | return ext |
| 50 | } |