错误的MIME“内容类型"的http.FileServer响应; [英] http.FileServer response with wrong mime "Content-Type"

查看:137
本文介绍了错误的MIME“内容类型"的http.FileServer响应;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用http.FileServer来提供mp3文件的目录,该模板然后是javascript中的src.但是,该响应使用Content-Type text/html而不是audio/mpeg.我如何设置FileServer响应的mime类型,我看到了这个问题

我得到的错误是:

HTTP "Content-Type" of "text/html" is not supported. Load of media resource http://localhost:5177/media/sample1.mp3 failed.

这不是内容类型的问题.当您请求mp3时,不会调用您的fs处理程序.您需要将/添加到图案/media中,并添加带状前缀这样的

http.Handle("/media/", http.StripPrefix("/media/", fs))

原因在 net/http.ServeMux

的文档中>

模式名称固定,有根的路径(例如"/favicon.ico")或有根的子树, 像"/images/"(注意斜杠).较长的模式优先 超过较短的那些,这样,如果同时注册了两个处理程序 "/images/"和"/images/thumbnails/",将要求使用后者 以"/images/thumbnails/"开头的路径,前者将收到请求 用于"/images/"子树中的任何其他路径.

仅使用/media即可注册路径的处理程序,但是带有斜杠的斜杠会将其视为rooted subtree并将在该树下处理请求.

I'm using http.FileServer to serve a directory of mp3 files, which my template then src in javascript. The response, however, uses the Content-Type text/html instead of audio/mpeg. How do I set the mime type which the FileServer responds with, I saw this question Setting the 'charset' property on the Content-Type header in the golang HTTP FileServer , but I'm still not sure how to override the mime type.

My code looks like the following:

fs := http.FileServer(http.Dir(dir))
http.Handle("/media", http.StripPrefix("/media", fs))
http.HandleFunc("/", p.playlistHandler)
http.ListenAndServe(":5177", nil)

and the error I get is:

HTTP "Content-Type" of "text/html" is not supported. Load of media resource http://localhost:5177/media/sample1.mp3 failed.

解决方案

It's not a problem of content types. Your fs handler isn't getting called when you request the mp3. You need to add a / to your pattern /media and the strip prefix like this

http.Handle("/media/", http.StripPrefix("/media/", fs))

The reason is in the documentation of net/http.ServeMux

Patterns name fixed, rooted paths, like "/favicon.ico", or rooted subtrees, like "/images/" (note the trailing slash). Longer patterns take precedence over shorter ones, so that if there are handlers registered for both "/images/" and "/images/thumbnails/", the latter handler will be called for paths beginning "/images/thumbnails/" and the former will receive requests for any other paths in the "/images/" subtree.

With just /media you're registering a handler for a path but with a trailing slash it considers it a rooted subtree and will serve requests under that tree.

这篇关于错误的MIME“内容类型"的http.FileServer响应;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆