http.DetectContentType
在日常开发中经常会用到检查文件类型 MIME 的功能,以此来判断文件类型是否满足条件。
在 Go 的标准库 net/http 包中提供一个简单的判断文件类型的方法 DetectContentType()。
它读取文件内容的前 512 个字节内容,返回一个 MIME 类型字符串例如 image/jpeg。对于无法识别的的文件类型,会返回 application/octet-stream。
bytes, err := os.ReadFile("/home/jh/test.jpeg")
if err != nil {
log.Fatal(err)
}
fmt.Println(http.DetectContentType(bytes)) // image/jpeg
DetectContentType 方法只支持有限的 MIME 类型,例如对于 office 文档经过测试只会返回 application/zip 类型,无法精准判断。
bytes1, err := os.ReadFile("/home/jh/123.xls")
if err != nil {
log.Fatal(err)
}
bytes2, err := os.ReadFile("/home/jh/123.docx")
if err != nil {
log.Fatal(err)
}
fmt.Println(http.DetectContentType(bytes1), http.DetectContentType(bytes2))
// application/zip application/zip
gabriel-vasile/mimetype
mimetype 包支持比标准库方法更广泛的 MIME 类型,拥有以下几个特点:
- 快速准确的
MIME类型和文件扩展名检测 - 支持
MIME类型的长列表 - 扩展其他文件格式的可能性
- 常用文件格式优先
- 文本文件与二进制文件的区别
- 安全的并发使用
f, _ := os.ReadFile("/home/jh/123.xls")
fmt.Println(mimetype.Detect(f))
// application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
f1, _ := os.ReadFile("/home/jh/123.docx")
fmt.Println(mimetype.Detect(f1))
// application/vnd.openxmlformats-officedocument.wordprocessingml.document
f2, _ := os.ReadFile("/home/jh/vip-uid.xlsx")
fmt.Println(mimetype.Detect(f2))
// application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
f3, _ := os.ReadFile("/home/jh/test.png")
fmt.Println(mimetype.Detect(f3))
// image/png