Files
whoswhip e5a2f47f47 organize project
took me a bit to figure out how to do this properly, but i believe it's improved my understanding of how go works
2026-11-21 16:18:30 -05:00

51 lines
1.1 KiB
Go

package uploads
import (
"fmt"
"io"
"mime"
"strings"
"github.com/gabriel-vasile/mimetype"
)
func detectMimeType(file io.ReadSeeker) (string, error) {
if _, err := file.Seek(0, io.SeekStart); err != nil {
return "", fmt.Errorf("rewind file: %w", err)
}
mtype, dtcErr := mimetype.DetectReader(file)
if _, err := file.Seek(0, io.SeekStart); err != nil {
return "", fmt.Errorf("rewind file: %w", err)
}
if dtcErr != nil {
return "", fmt.Errorf("detect MIME type: %w", dtcErr)
}
return mtype.String(), nil
}
func normalizeMIMEType(contentType string) string {
const plaintext = "text/plain; charset=utf-8"
mediaType, _, err := mime.ParseMediaType(contentType)
if err != nil {
return plaintext
}
if strings.HasSuffix(mediaType, "+xml") {
return plaintext
}
switch mediaType {
case "text/html", "text/javascript", "application/javascript",
"application/ecmascript", "text/ecmascript", "application/xml",
"text/xml", "text/xsl",
"text/css", "application/wasm":
return plaintext
case "application/pdf":
return "application/octet-stream"
default:
return contentType
}
}