HTML输出被解释为纯文本而不是作为HTML接收。

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

HTML output is being interpreted as plain text instead of being received as 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标签中,并随后被包裹在一个新文档中。

那么是怎么回事呢?为什么Go默认将其视为纯文本而不是以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(&quot;test&quot;)
	t, _ := template.ParseFiles(&quot;base.html&quot;)
	t.Execute(w, &quot;&quot;)
})

server := &amp;http.Server{
	Addr:           &quot;:9999&quot;,
	Handler:        requestHandler,
	ReadTimeout:    10 * time.Second,
	WriteTimeout:   10 * time.Second,
	MaxHeaderBytes: 1 &lt;&lt; 20,
}

log.Fatal(server.ListenAndServe())

The contents of base.html are as follows:

&lt;DOCTYPE html&gt;
&lt;html&gt;
	&lt;body&gt;
		base.html
	&lt;/body&gt;
&lt;/html&gt;

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

得分: 10

你需要添加一个带有Content-Type的头部。

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

英文:

You need to add a header with the Content-Type

 w.Header().Set(&quot;Content-Type&quot;, &quot;text/html&quot;)

huangapple
  • 本文由 发表于 2014年8月1日 02:10:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/25066071.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定