Skip to content

A simple golang library for detecting the MIME type and file extension, based on magic numbers

License

Notifications You must be signed in to change notification settings

adicostil/mimetype

 
 

Repository files navigation

mimetype

A package for detecting MIME types and extensions based on magic numbers

No C bindings, zero dependencies and thread safe

Build Status Documentation Go report card Go report card License

Features

  • fast and precise MIME type and file extension detection
  • long list of supported MIME types
  • common file formats are prioritized
  • small and simple API
  • handles MIME type aliases
  • thread safe
  • low memory usage: besides the file header, almost zero allocs

Install

go get github.com/gabriel-vasile/mimetype

Usage

There are quick examples and GoDoc for full reference.

Structure

mimetype uses an hierarchical structure to keep the MIME type detection logic. This reduces the number of calls needed for detecting the file type. The reason behind this choice is that there are file formats used as containers for other file formats. For example, Microsoft Office files are just zip archives, containing specific metadata files. Once a file a file has been identified as a zip, there is no need to check if it is a text file, but it is worth checking if it is an Microsoft Office file.

To prevent loading entire files into memory, when detecting from a reader or from a file mimetype limits itself to reading only the header of the input.

structure

Performance

Thanks to the hierarchical structure, searching for common formats first, and careful memory allocations mimetype has an order of magnitude faster detections.

Benchmarks were run on an Intel Xeon Gold 6136 24 core CPU @ 3.00GHz.

                                 filetype            mimetype
BenchmarkMatchTar-24            3778 ns/op          250 ns/op
BenchmarkMatchZip-24            4884 ns/op          524 ns/op
BenchmarkMatchJpeg-24            839 ns/op          103 ns/op
BenchmarkMatchGif-24             751 ns/op          139 ns/op
BenchmarkMatchPng-24            1176 ns/op          165 ns/op

Contributing

See CONTRIBUTING.md.

About

A simple golang library for detecting the MIME type and file extension, based on magic numbers

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Go 100.0%