Home  >  Article  >  Backend Development  >  Why Does Go Send HTML Output as Plain Text in a Template?

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-28 06:53:29985browse

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

Go HTML Output as Plain Text

Consider the following code setup:

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

The "base.html" file contains the following HTML:

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

Upon running the server and navigating to the page, the HTML from the template is displayed verbatim, enclosed within

 tags and a new document wrapper.</p>
<p>The reason for this behavior lies in the absence of a "Content-Type" header for the response. By default, Go treats the output as plain text. To correct this, add the following line before executing the template:</p>
<pre class="brush:php;toolbar:false"><code class="go">w.Header().Set("Content-Type", "text/html")</code>

With this adjustment, the browser will correctly interpret the output as HTML and render it appropriately.

The above is the detailed content of Why Does Go Send HTML Output as Plain Text in a Template?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn