为Fprint进行多个响应.WriteHeader调用

huangapple go评论83阅读模式
英文:

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 = `&lt;!doctype html&gt;
&lt;html&gt;
	&lt;head&gt;
		&lt;title&gt;%s&lt;/title&gt;
	&lt;/head&gt;
	&lt;body&gt;
	&lt;h1&gt;%s&lt;/h1&gt;
	&lt;div&gt;&lt;img src=&quot;images/%s&quot;&gt;&lt;/div&gt;
	&lt;/body&gt;
&lt;/html&gt;
`

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, tmpl, &quot;Hello, world!&quot;, &quot;Hello, world!&quot;, &quot;gopher.png&quot;)
}

func main() {
	http.HandleFunc(&quot;/&quot;, handler)
	http.Handle(&quot;/images/&quot;, http.FileServer(http.Dir(&quot;images/&quot;)))
	http.ListenAndServe(&quot;:3000&quot;, nil)
}

huangapple
  • 本文由 发表于 2014年10月18日 04:35:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/26433089.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定