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 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号