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.

GoFile Upload

Code

snippet
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

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.