mimetype

基于幻数的 MIME 类型和文件扩展检测的快速 golang 库。「A fast golang library for MIME type and file extension detection, based on magic numbers」

Github星跟踪图

Features

  • fast and precise MIME type and file extension detection
  • long list of supported MIME types
  • posibility to extend with other file formats
  • common file formats are prioritized
  • safe for concurrent usage

Install

go get github.com/gabriel-vasile/mimetype

Usage

mtype := mimetype.Detect([]byte)
// OR
mtype, err := mimetype.DetectReader(io.Reader)
// OR
mtype, err := mimetype.DetectFile("/path/to/file")
fmt.Println(mtype.String(), mtype.Extension())

See the runnable Go Playground examples.

Usage'

Only use libraries like mimetype as a last resort. Content type detection
using magic numbers is slow, inaccurate, and non-standard. Most of the times
protocols have methods for specifying such metadata; e.g., Content-Type header
in HTTP and SMTP.

Structure

mimetype uses a 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 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.

Performance

Thanks to the hierarchical structure, searching for common formats first,
and limiting itself to file headers, mimetype matches the performance of
stdlib http.DetectContentType while outperforming the alternative package.

                            mimetype  http.DetectContentType      filetype
BenchmarkMatchTar-24       250 ns/op         400 ns/op           3778 ns/op
BenchmarkMatchZip-24       524 ns/op         351 ns/op           4884 ns/op
BenchmarkMatchJpeg-24      103 ns/op         228 ns/op            839 ns/op
BenchmarkMatchGif-24       139 ns/op         202 ns/op            751 ns/op
BenchmarkMatchPng-24       165 ns/op         221 ns/op           1176 ns/op

Contributing

See CONTRIBUTING.md.

主要指标

概览
名称与所有者gabriel-vasile/mimetype
主编程语言Go
编程语言Go (语言数: 1)
平台
许可证MIT License
所有者活动
创建于2018-07-02 07:15:29
推送于2025-07-21 13:03:59
最后一次提交2025-07-21 18:03:38
发布数54
最新版本名称v1.4.9 (发布于 )
第一版名称v0.1.0 (发布于 )
用户参与
星数1.8k
关注者数17
派生数171
提交数599
已启用问题?
问题数171
打开的问题数25
拉请求数243
打开的拉请求数16
关闭的拉请求数255
项目设置
已启用Wiki?
已存档?
是复刻?
已锁定?
是镜像?
是私有?