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

进行多次响应.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
    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)
    }
    
    点赞 评论

相关推荐