duan0417 2014-10-17 20:35
浏览 43
已采纳

进行多次响应.WriteHeader调用Fprint

I want to print out the text message first and below the text, diplay the image. But I am getting http: multiple response.WriteHeader calls errors.

How do I serve iamges and text using one hadler in one single page?

func handler(w http.ResponseWriter, r *http.Request) {
  fmt.Fprint(w, "Hello, world!")
  fp := path.Join("images", "gopher.png")
  http.ServeFile(w, r, fp)
}

func main() {
  http.HandleFunc("/", handler)
  http.ListenAndServe(":3000", nil)
}
  • 写回答

1条回答 默认 最新

  • doubi4814 2014-10-17 20:38
    关注

    You can't write text then call ServeFile to output a binary picture after the text.

    If you want to serve text with the image then use html, setup a static file handler and use html:

    var tmpl = `<!doctype html>
    <html>
        <head>
            <title>%s</title>
        </head>
        <body>
        <h1>%s</h1>
        <div><img src="images/%s"></div>
        </body>
    </html>
    `
    
    func handler(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, tmpl, "Hello, world!", "Hello, world!", "gopher.png")
    }
    
    func main() {
        http.HandleFunc("/", handler)
        http.Handle("/images/", http.FileServer(http.Dir("images/")))
        http.ListenAndServe(":3000", nil)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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