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.

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

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作