首页  >  文章  >  后端开发  >  为什么 Go 在模板中以纯文本形式发送 HTML 输出?

为什么 Go 在模板中以纯文本形式发送 HTML 输出?

Barbara Streisand
Barbara Streisand原创
2024-10-28 06:53:29985浏览

Why Does Go Send HTML Output as Plain Text in a Template?

将 HTML 输出为纯文本

考虑以下代码设置:

<code class="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” " 文件包含以下 HTML:

<code class="html"><!DOCTYPE html>
<html>
    <body>
        base.html
    </body>
</html></code>

运行服务器并导航到页面时,模板中的 HTML 将逐字显示,包含在

 内标签和新的文档包装器。<p>此行为的原因在于响应缺少“Content-Type”标头。默认情况下,Go 将输出视为纯文本。要纠正此问题,请在执行模板之前添加以下行:</p><pre class="brush:php;toolbar:false"><code class="go">w.Header().Set("Content-Type", "text/html")</code>

通过此调整,浏览器将正确地将输出解释为 HTML 并正确呈现它。

以上是为什么 Go 在模板中以纯文本形式发送 HTML 输出?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn