Resolve MIME Types With mime.TypeByExtension
Look up canonical MIME types by extension with mime.TypeByExtension: built-in table entries come back directly, unknown extensions return an empty string.
Code
package main
import (
"fmt"
"mime"
)
func main() {
// 扩展名 → MIME:内置表覆盖常见类型,无需读文件内容
for _, ext := range []string{".html", ".css", ".png", ".json"} {
fmt.Printf("%-6s -> %s\n", ext, mime.TypeByExtension(ext))
}
// 未知扩展名返回空串:这里应该交给魔数嗅探兜底
if got := mime.TypeByExtension(".xyz"); got == "" {
fmt.Println(".xyz -> (empty, sniff the bytes instead)")
}
}How the pieces connect
Resolve MIME Types With mime.TypeByExtension is built around the function main.
Iteration happens inside for _, ext := range []string{".html", ".css", ".png", ".json"} — everything outside it runs once.
Applying it
The demo output is labeled (.xyz -> (empty, sniff the bytes instead)), so every line in the printed output names the step that produced it.
Statements that matter
for _, ext := range []string{".html", ".css", ".png", ".json"} {
fmt.Printf("%-6s -> %s\n", ext, mime.TypeByExtension(ext))
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.MIME Type LookupResolve a file extension, file name, or MIME type to its media type, category, and related extensions using a local reference table.Quoted-Printable CodecEncode and decode quoted-printable (RFC 2045) used by email, escaping non-ASCII bytes and wrapping long lines.
FAQ
- What does Resolve MIME Types With mime.TypeByExtension print when run?
- No setup needed: run the file and look for labeled lines like `.xyz -> (empty, sniff the bytes instead)` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.