【问题标题】:http.FileServer response with wrong mime "Content-Type"http.FileServer 响应错误的 mime “Content-Type”
【发布时间】:2017-01-24 00:10:37
【问题描述】:

我正在使用 http.FileServer 提供一个 mp3 文件目录,然后我的模板在 javascript 中使用 src。但是,响应使用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)

我得到的错误是:

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

【问题讨论】:

    标签: javascript go content-type mime fileserver


    【解决方案1】:

    这不是内容类型的问题。当您请求 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,并将在该树下处理请求。

    【讨论】:

      猜你喜欢
      • 2019-03-29
      • 1970-01-01
      • 2020-10-05
      • 2016-02-27
      • 1970-01-01
      • 2019-09-05
      • 2011-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多