我想存储从 GET 请求获得的响应的 MIME 类型。我已经使用了该DetectContentType
函数,但它text/plain; charset=utf-8
为我提供了 js 和 css 资源。我必须区分每个 url 的文件类型,并且为此目的我依赖 MIME 类型。
response, error := http.Get(url)
if error == nil {
contentType := response.Header.Get("Content-Type")
// ...
}
Run Code Online (Sandbox Code Playgroud)
只给我内容类型。
听起来你可以使用 Go 的 mime 包。mime 包中的 TypeByExtension 方法可能适合您的需求。https://golang.org/pkg/mime/#TypeByExtension
我相信这使用了主机系统的 mime 类型表。此方法确定的 mime 类型可能与远程服务器报告的 mime 类型不同。
import "mime"
func DetermineMimeType (fileExtension string) string {
return mime.TypeByExtension(fileExtension)
}
Run Code Online (Sandbox Code Playgroud)
请务必传递包含句点的完整文件扩展名,例如“.js”或“.css”。只是为了涵盖所有情况,如果您无法确定文件的扩展名或者此方法不返回 mime 类型,则可能默认为远程服务器报告的 mime 类型。