猿问

去多个 response.WriteHeader 调用 Fprint

我想先打印出文本消息,然后在文本下方,显示图像。但我得到http: multiple response.WriteHeader calls的错误。


如何服务iamges和文字使用一个哈德勒在一个单一的页面?


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)

}


开满天机
浏览 206回答 1
1回答

Helenr

不能写文本然后调用ServeFile在文本后面输出一个二进制图片。如果你想为文字与图像,然后使用HTML,设置一个静态文件处理程序,并用html:var tmpl = `<!doctype html><html>&nbsp; &nbsp; <head>&nbsp; &nbsp; &nbsp; &nbsp; <title>%s</title>&nbsp; &nbsp; </head>&nbsp; &nbsp; <body>&nbsp; &nbsp; <h1>%s</h1>&nbsp; &nbsp; <div><img src="images/%s"></div>&nbsp; &nbsp; </body></html>`func handler(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; fmt.Fprintf(w, tmpl, "Hello, world!", "Hello, world!", "gopher.png")}func main() {&nbsp; &nbsp; http.HandleFunc("/", handler)&nbsp; &nbsp; http.Handle("/images/", http.FileServer(http.Dir("images/")))&nbsp; &nbsp; http.ListenAndServe(":3000", nil)}
随时随地看视频慕课网APP

相关分类

Go
我要回答