Media types, also known as MIME types, are a standard that indicates the nature and format of some data. You most likely met media types in HTTP requests, send to and received from the webserver as HTTP headers, ex: Content-Type: application/javascript
.
Golang standard library provides support for MIME types through two APIs:
-
the
mime
package, which has functions for retrieving the MIME type given a file extension:
fmt.Println(mime.TypeByExtension(".txt")) // Output: text/plain; charset=utf-8
-
the
http.DetectContentType
function which, given a fragment of a file, returns its MIME type:
fmt.Println(http.DetectContentType([]byte("some text content of a file"))) // Output: text/plain; charset=utf-8
Even if they work as intended, these two approaches have their limitations. mime
can be easily tricked: anyone can change the extension of a file from .exe to .jpg. http.DetectContentType
on the other hand is a more careful option, as it looks at the actual data in a file. However it suffers from a limited number of detected MIME types, with notable missing entries for office documents, audio files and some archives.
Beyond the standard library is the land of user libraries where Go has three candidates for MIME types libraries:
Out of the three, magicmime is the most accurate, but it requires C cross compilation and libmagic-dev installed. The other two implemented the detection algorithms in pure Go, so they can just be imported. Out of them, mimetype features a bigger list of supported MIME types, but most importantly the identification is deterministic, unlike filetype which returns different results when testing the same data.
Reference experiment: https://github.com/ppai-plivo/go-mime-lib-compare
Top comments (0)