DetectMimeType returns the MIME type for a file by reading its first 512 bytes and inspecting the content (magic bytes). For text-based files that http.DetectContentType cannot distinguish (e.g. source code vs plain text), it falls back to extension matching. This is the canonical implementation use
(filePath string)
| 185 | // it falls back to extension matching. This is the canonical implementation |
| 186 | // used across all packages for consistency. |
| 187 | func DetectMimeType(filePath string) string { |
| 188 | // Content sniffing — reliably detects images, PDF, etc. |
| 189 | if ct := detectMimeTypeFromFile(filePath); ct != "application/octet-stream" { |
| 190 | return ct |
| 191 | } |
| 192 | |
| 193 | // http.DetectContentType returns "application/octet-stream" for text |
| 194 | // files it can't classify, so fall back to extension for those. |
| 195 | if isTextExtension(strings.ToLower(filepath.Ext(filePath))) { |
| 196 | return "text/plain" |
| 197 | } |
| 198 | return "application/octet-stream" |
| 199 | } |
| 200 | |
| 201 | // detectMimeTypeFromFile reads the first 512 bytes of a file and uses |
| 202 | // content-based detection (magic bytes) to determine the MIME type. |