doujiu8918 2013-10-30 18:13
浏览 113
已采纳

Golang:io.Copy(httpReponseWriter,os.File)与http.ServeFile()

Before realizing that the http package has a builtin ServeFile method, I implemented a static handler more or less like this:

func StaticHandler(w http.ResponseWriter, r *http.Request) {
    filename := mux.Vars(r)["static"] // using gorilla/mux
    f, err := os.Open(fmt.Sprintf("%v/static/%v", webroot, filename))

    if err != nil {
        http.NotFound(w, r)
        return
    }

    defer f.Close()

    io.Copy(w, f)
}

And, for example, linked my style sheet and images this way:

<img href="/image.jpg" />
<link rel="stylesheet" type="text/css" href="/stylesheet.css">

This worked just fine, except for one thing: my linked stylesheet was not being applied by the browser (tested in Chrome, Firefox, Midori). The stylesheet could be served ( visiting MYSITE/stylesheet.css displayed the css plaintext) and images would load normally in a page, but none of my pages would have any style.

Any ideas as to why?

  • 写回答

1条回答 默认 最新

  • dporu02280 2013-10-30 18:54
    关注

    Simple answer: headers were wrong.

    Go will supply correct headers for html, jpgs, and pngs, but css (and js) files are left as "text/plain" rather than "text/css" and "text/javascript".

    Go source shows the handling being invoked, I believe.

    Anyways, setting the content type via:

    w.Header().Set("Content-Type", "text/css; charset=utf-8")
    

    Did the trick.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加