dongsuo9982 2014-07-31 18:10
浏览 116
已采纳

Golang html输出被解释为纯文本,而不是被接收为html

I'm sure this is just something dumb I'm doing, but I'm new to Go, so not sure what's going on here. I have the following basic setup.

requestHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    t := template.New("test")
    t, _ := template.ParseFiles("base.html")
    t.Execute(w, "")
})

server := &http.Server{
    Addr:           ":9999",
    Handler:        requestHandler,
    ReadTimeout:    10 * time.Second,
    WriteTimeout:   10 * time.Second,
    MaxHeaderBytes: 1 << 20,
}

log.Fatal(server.ListenAndServe())

The contents of base.html are as follows:

<DOCTYPE html>
<html>
    <body>
        base.html
    </body>
</html>

When I run the server and load the page, I see the HTML inside the template verbatim -- instead of the interpreted version. Turns out, the template is being wrapped in pre tags, and is subsequently being wrapped in a new document.

So what's going on? Why is go by default treating this as plain text rather than sending it over as html, so that the browser can render it properly? Surely this must be a simple misunderstanding, but not getting anything in searches. Ideas?

  • 写回答

1条回答 默认 最新

  • dsd57259 2014-07-31 18:55
    关注

    You need to add a header with the Content-Type

     w.Header().Set("Content-Type", "text/html")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100