A MIME type, also called a content type, identifies the format of a file or HTTP payload. Common values include image/png, application/octet-stream, and application/json. In Go, MIME types help validate uploads, reject unexpected responses, and select API representations. section 10.2.5 section 11.2.2
Validate an uploaded file using progressively more trustworthy signals:
- Read the request's Content-Type header; it may provide a specific type such as image/png or the generic application/octet-stream. section 10.2.5
- Inspect the filename extension and map it with mime.TypeByExtension. section 10.2.5
- Read initial bytes and call http.DetectContentType to infer the type from file contents. section 10.2.5
- Treat headers and extensions as untrusted hints; content parsing is harder and more resource-intensive, but more trusted. section 10.2.5
file, header, err := r.FormFile("file")
contentType := header.Header["Content-Type"][0]
Extracts the uploaded Content-Type from multipart.FileHeader. section 10.2.5
file, header, err := r.FormFile("file")
extension := filepath.Ext(header.Filename)
type := mime.TypeByExtension(extension)
Maps an uploaded filename extension to a MIME type with the standard library. section 10.2.5
file, header, err := r.FormFile("file")
buffer := make([]byte, 512)
_, err = file.Read(buffer)
filetype := http.DetectContentType(buffer)
Reads 512 bytes and detects the content type from the file's data. section 10.2.5
HTTP clients can also use MIME types to interpret errors and negotiate API versions. Check Content-Type alongside the status code before decoding an error response, and use versioned vendor types such as application/vnd.mytodos.json; version=2.0 in Accept and response headers. section 11.2.2 section 11.4.2

