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

Nev*_*ore 6 javascript mime content-type fileserver go

我正在使用 http.FileServer 来提供 mp3 文件的目录,然后我的模板src在 javascript 中。但是,响应使用Content-Type text/html代替audio/mpeg。如何设置 FileServer 响应的 mime 类型,我看到了这个问题Setting the 'charset' property on the Content-Type header in the golang HTTP FileServer,但我仍然不确定如何覆盖 mime 类型。

我的代码如下所示:

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

我得到的错误是:

HTTP "Content-Type" of "text/html" is not supported. Load of media resource http://localhost:5177/media/sample1.mp3 failed.
Run Code Online (Sandbox Code Playgroud)

jcb*_*lkr 7

这不是内容类型的问题。fs当您请求 mp3 时,您的处理程序不会被调用。您需要/在您的模式/media和条带前缀中添加一个,如下所示

http.Handle("/media/", http.StripPrefix("/media/", fs))
Run Code Online (Sandbox Code Playgroud)

原因在net/http.ServeMux的文档中

模式命名固定的根路径,例如“/favicon.ico”,或根子树,例如“/images/”(注意尾部斜杠)。较长的模式优先于较短的模式,因此,如果同时为“/images/”和“/images/thumbnails/”注册了处理程序,则将为以“/images/thumbnails/”开头的路径调用后一个处理程序,而前者则将被调用将接收对“/images/”子树中任何其他路径的请求。

只要/media您为路径注册一个处理程序,但带有尾部斜杠,它就会认为它是一个rooted subtree并将在该树下提供请求。