英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论