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

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

Go multiple response.WriteHeader calls for Fprint

问题

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

如何在一个处理程序中同时提供图像和文本,以在单个页面中显示?

  1. func handler(w http.ResponseWriter, r *http.Request) {
  2. fmt.Fprint(w, "Hello, world!")
  3. fp := path.Join("images", "gopher.png")
  4. http.ServeFile(w, r, fp)
  5. }
  6. func main() {
  7. http.HandleFunc("/", handler)
  8. http.ListenAndServe(":3000", nil)
  9. }
英文:

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?

  1. func handler(w http.ResponseWriter, r *http.Request) {
  2. fmt.Fprint(w, "Hello, world!")
  3. fp := path.Join("images", "gopher.png")
  4. http.ServeFile(w, r, fp)
  5. }
  6. func main() {
  7. http.HandleFunc("/", handler)
  8. http.ListenAndServe(":3000", nil)
  9. }

答案1

得分: 0

你不能先写文本,然后调用ServeFile来输出文本后的二进制图片。

如果你想在图片中显示文本,可以使用HTML,设置一个静态文件处理程序,并使用HTML代码:

  1. var tmpl = `<!doctype html>
  2. <html>
  3. <head>
  4. <title>%s</title>
  5. </head>
  6. <body>
  7. <h1>%s</h1>
  8. <div><img src="images/%s"></div>
  9. </body>
  10. </html>
  11. `
  12. func handler(w http.ResponseWriter, r *http.Request) {
  13. fmt.Fprintf(w, tmpl, "Hello, world!", "Hello, world!", "gopher.png")
  14. }
  15. func main() {
  16. http.HandleFunc("/", handler)
  17. http.Handle("/images/", http.FileServer(http.Dir("images/")))
  18. http.ListenAndServe(":3000", nil)
  19. }
英文:

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:

  1. var tmpl = `&lt;!doctype html&gt;
  2. &lt;html&gt;
  3. &lt;head&gt;
  4. &lt;title&gt;%s&lt;/title&gt;
  5. &lt;/head&gt;
  6. &lt;body&gt;
  7. &lt;h1&gt;%s&lt;/h1&gt;
  8. &lt;div&gt;&lt;img src=&quot;images/%s&quot;&gt;&lt;/div&gt;
  9. &lt;/body&gt;
  10. &lt;/html&gt;
  11. `
  12. func handler(w http.ResponseWriter, r *http.Request) {
  13. fmt.Fprintf(w, tmpl, &quot;Hello, world!&quot;, &quot;Hello, world!&quot;, &quot;gopher.png&quot;)
  14. }
  15. func main() {
  16. http.HandleFunc(&quot;/&quot;, handler)
  17. http.Handle(&quot;/images/&quot;, http.FileServer(http.Dir(&quot;images/&quot;)))
  18. http.ListenAndServe(&quot;:3000&quot;, nil)
  19. }

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:

确定