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

Barbara Streisand
Release: 2024-10-28 06:53:29
Original
998 people have browsed it

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())
Copy after login

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

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

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>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"><code class="go">w.Header().Set("Content-Type", "text/html")</code>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!