简体   繁体   English

http.FileServer响应错误的mime“Content-Type”

[英]http.FileServer response with wrong mime “Content-Type”

I'm using http.FileServer to serve a directory of mp3 files, which my template then src in javascript. 我正在使用http.FileServer来提供mp3文件的目录,我的模板然后在javascript中使用src The response, however, uses the Content-Type text/html instead of audio/mpeg . 但是,响应使用Content-Type text/html而不是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. 如何设置FileServer响应的mime类型,我看到了这个问题在golang HTTP FileServer中的Content-Type标头上设置'charset'属性 ,但我仍然不确定如何覆盖mime类型。

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. 当你请求mp3时,你的fs处理程序没有被调用。 You need to add a / to your pattern /media and the strip prefix like this 您需要像这样在模式/media和条带前缀中添加/

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

The reason is in the documentation of net/http.ServeMux 原因在于net / http.ServeMux的文档

Patterns name fixed, rooted paths, like "/favicon.ico", or rooted subtrees, like "/images/" (note the trailing slash). 模式名称固定,带根的路径,如“/favicon.ico”,或带根的子树,如“/ images /”(请注意尾部斜杠)。 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. 较长的模式优先于较短的模式,因此如果有“/ images /”和“/ images / thumbnails /”注册的处理程序,则后面的处理程序将被调用以“/ images / thumbnails /”开头的路径和前者将收到“/ images /”子树中任何其他路径的请求。

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. 使用/media您正在为路径注册处理程序,但是使用尾部斜杠,它会将其视为有rooted subtree ,并将在该树下提供请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM