【问题标题】:Go multiple response.WriteHeader calls for FprintGo multiple response.WriteHeader 调用 Fprint
【发布时间】:2014-12-13 12:19:22
【问题描述】:

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

【问题讨论】:

    标签: http go


    【解决方案1】:

    不能写文本然后调用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)
    }
    

    【讨论】:

    • 有没有其他方式来提供文字和图片?
    • @EPSILONsdfsdfdsf 使用 html。
    • 这适用于静态文件,但是当我服务时,服务器找不到文件
    • @EPSILONsdfsdfdsf 您确定为文件服务器设置了正确的路径吗? golang.org/pkg/net/http/#FileServer
    • 您也可以将图像嵌入为 base64 编码的数据 URI,但我不知道该怎么做。
    猜你喜欢
    • 1970-01-01
    • 2016-06-06
    • 2020-07-29
    • 1970-01-01
    • 2019-01-22
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    • 2018-06-11
    相关资源
    最近更新 更多