我想先打印出短信,然后在文字下方显示图像。但是我遇到了http: multiple response.WriteHeader calls
错误。
如何在一个页面中使用一个hadler来提供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)
}
您无法编写文本,然后调用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)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句