英文:
Go multiple response.WriteHeader calls for Fprint
问题
我想先打印出文本消息,然后在文本下方显示图像。但是我遇到了http: multiple response.WriteHeader calls
错误。
如何在一个处理程序中同时提供图像和文本,以在单个页面中显示?
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)
}
英文:
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
得分: 0
你不能先写文本,然后调用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)
}
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论