How can I get MIME type of the http response with media subtype?

huangapple go评论88阅读模式
英文:

How can I get MIME type of the http response with media subtype?

问题

我想要存储从GET请求获取到的响应的MIME类型。我已经使用了DetectContentType函数,但它对于js和css资源都给出了text/plain; charset=utf-8。我需要区分每个URL的文件类型,而我依赖于MIME类型来实现这个目的。

response, error := http.Get(url)
if error == nil {
    contentType := response.Header.Get("Content-Type")
    // ...
}

只给出了内容类型。

英文:

I want to store MIME type of the response obtained from GET request. I have used the DetectContentType function but it gives me text/plain; charset=utf-8 for both js and css resource. I have to distinguish the filetype for each url and I'm depending on MIME type for that purpose.

response, error := http.Get(url) 
if error == nil { 
    contentType := response.Header.Get("Content-Type") 
    // ... 
}

Only gives me content type.

答案1

得分: 4

看起来你可以使用Go的mime包。mime包中的TypeByExtension方法可能适合你的需求。https://golang.org/pkg/mime/#TypeByExtension

我相信这个方法使用了主机系统的mime类型表。由于这种方法确定的mime类型可能与远程服务器报告的mime类型不同。

import "mime"

func DetermineMimeType(fileExtension string) string {
    return mime.TypeByExtension(fileExtension)
}

确保传入完整的文件扩展名,包括句点,例如".js"或".css"。为了涵盖所有情况,如果无法确定文件的扩展名或此方法不返回mime类型,则可以默认使用远程服务器报告的mime类型。

英文:

Sounds like you could use Go's mime package. The TypeByExtension method in the mime package might suit your needs. https://golang.org/pkg/mime/#TypeByExtension

I believe this uses the host system's mime type table. It is possible that the mime type determined by this method could be different than the mime type reported by the remote server.

import "mime"

func DetermineMimeType (fileExtension string) string {
	return mime.TypeByExtension(fileExtension)
}

Be sure to pass in the full file extension including the period, for example ".js" or ".css". Just to cover all the cases, if you can't determine the file's extension or this method doesn't return a mime type then perhaps default to the mime type reported by the remote server.

huangapple
  • 本文由 发表于 2015年10月8日 14:23:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/33008063.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定