我想先打印出文本消息,然后在文本下方显示图像。
但我收到了 http: multiple response.WriteHeader calls
错误。
我如何在一个页面中使用一个 hadler 提供图像和文本?
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)
}
最佳答案
不能写文本然后调用ServeFile在文本后输出二进制图片。
如果你想用图像提供文本然后使用 html,设置一个静态文件处理程序并使用 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)
}
关于http - 转到多个 response.WriteHeader 调用 Fprint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26433089/