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

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

我正在使用 http.FileServer 来提供一个 mp3 文件目录,然后我的模板 src 在 javascript 中。但是,响应使用 Content-Type text/html 而不是 audio/mpeg。如何设置 FileServer 响应的 mime 类型,我看到了这个问题 ,但我仍然不确定如何覆盖 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

的文档中

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.

/media 您正在为路径注册处理程序,但尾部斜杠将其视为 rooted subtree 并将在该树下处理请求。