http.文件服务器响应的mime "Content-Type"错误

http.FileServer response with wrong mime "Content-Type"

本文关键字:quot Content-Type 错误 mime 文件服务器 响应 http      更新时间:2023-09-26

我使用http。文件服务器服务的mp3文件目录,其中我的模板然后src在javascript。响应,然而,使用Content-Type text/html而不是audio/mpeg。我如何设置FileServer响应的mime类型,我看到这个问题设置'charset'属性上的内容类型头在golang HTTP文件服务器,但我仍然不确定如何覆盖mime类型。

我的代码如下所示:

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

得到的错误是:

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/"answers"/images/thumbnails/",后一个处理程序将被调用以"/images/thumbnails/"开头的路径和前者将接收请求查看"/images/"子树中的其他路径

只有/media,你注册一个处理程序的路径,但与尾斜杠它认为它是一个rooted subtree,并将服务于该树下的请求。