Sniff Upload Type With http.DetectContentType
Trust magic bytes over file extensions: http.DetectContentType inspects the first 512 bytes and returns the canonical MIME type for upload validation.
Code
package main
import (
"fmt"
"net/http"
)
func main() {
// 上传校验:扩展名和 Content-Type 请求头都可伪造,魔数嗅探结果才用于放行
uploads := []struct {
name string
head []byte
}{
{"report.csv", []byte("id,name,total\n1,ada,42\n")},
{"notes.json", []byte("{\"user\":\"ada\",\"ok\":true}")},
{"payload.png", []byte("\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR")},
{"blob.bin", []byte{0x00, 0x01, 0x02, 0xFF, 0xFE}},
}
for _, up := range uploads {
// 只看前 512 字节,与浏览器嗅探算法一致
fmt.Printf("%-12s -> %s\n", up.name, http.DetectContentType(up.head))
}
}The flow of the file
Sniff Upload Type With http.DetectContentType is built around the function main.
Repetition is confined to for _, up := range uploads — the rest of the file is straight-line.
What to watch for
- Nothing to vet in a supply-chain review — the file pulls in no packages.
Statements that matter
for _, up := range uploads {
// 只看前 512 字节,与浏览器嗅探算法一致
fmt.Printf("%-12s -> %s\n", up.name, http.DetectContentType(up.head))
}
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.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.Set-Cookie ParserParse one or more Set-Cookie header values into the cookie name, value, and attributes like Path, Domain, Expires, Max-Age, Secure, HttpOnly, and SameSite.
FAQ
- How do you run Sniff Upload Type With http.DetectContentType?
- Run the file on its own; every call resolves against the standard surface it already imports.
Report a problem with this exampleOpens a pre-filled issue on GitHub.