Golang的html输出被解释为纯文本,而不是被接收为html [英] Golang html output is being interpreted as plain text instead of being received as html

查看:1160
本文介绍了Golang的html输出被解释为纯文本,而不是被接收为html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确定这只是我正在做的事,但我是Go的新手,所以不知道这里发生了什么。我有以下基本设置:

  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())

base.html的内容如下:

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

当我运行服务器并加载页面时,我会逐字看到模板内的HTML - 的解释版本。事实证明,该模板被封装在 pre 标签中,随后被包装在一个新文档中。

所以发生了什么?为什么默认情况下将其视为纯文本而不是将其作为html发送,以便浏览器可以正确渲染它?当然,这肯定是一个简单的误解,但没有得到任何搜索。想法?

解决方案

您需要添加一个包含Content-Type的标题

  w.Header()。Set(Content-Type,text / 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?

解决方案

You need to add a header with the Content-Type

 w.Header().Set("Content-Type", "text/html")

这篇关于Golang的html输出被解释为纯文本,而不是被接收为html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆