http - 转到多个 response.WriteHeader 调用 Fprint

标签 http go

我想先打印出文本消息,然后在文本下方显示图像。 但我收到了 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/

相关文章:

http - 登录后重定向和 session 数据传输到另一个服务器/域

java - API 网关自定义授权方 : Control error message and code

go - 在 Golang 中绕过 http_proxy

ios - 使用 http 和 https 移动网络服务

php - 在 PHP 脚本中处理 HTTP 请求参数

go - 在 Go 中将一个 writer 包装在一个 reader 中?

json - 无法在 gqlgen 中生成标量 JSON

go - 如何使用RWMutex和升级锁

go - 如何获得一天中的秒数

Node.js Express - 在完成处理整个请求之前提供 HTTP 响应