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

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

问题描述

我确定这只是我正在做的愚蠢的事情,但是我是Go的新手,所以不确定这是怎么回事.我有以下基本设置.

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

base.html的内容如下:

The contents of base.html are as follows:

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

当我运行服务器并加载页面时,我看到模板内的HTML是逐字显示的-而不是解释后的版本.事实证明,模板被包装在 pre 标签中,随后被包装在新文档中.

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.

那是怎么回事?为什么默认情况下go会将其视为纯文本而不是将其作为html发送,以便浏览器可以正确呈现它?当然,这肯定是一个简单的误解,但搜索没有任何结果.想法?

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?

推荐答案

您需要添加具有Content-Type的标题

You need to add a header with the Content-Type

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

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

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