Why is My Go HTML Output Displayed as Plain Text?

DDD
Release: 2024-10-29 20:39:29
Original
334 people have browsed it

Why is My Go HTML Output Displayed as Plain Text?

Go's HTML Output Interpretation Issue Explained

In Go, sending HTML output via HTTP can sometimes result in the output being interpreted as plaintext. This occurs when the response lacks the appropriate headers specifying the content type.

Consider the following code:

<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

With base.html containing the following:

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

When you load the served page, you'll observe that the HTML is displayed verbatim instead of being rendered. This is because the response lacks the Content-Type header, which should be set to text/html.

To resolve this issue, you need to add the following line before executing the template:

<code class="go">w.Header().Set("Content-Type", "text/html")</code>
Copy after login

This header informs the browser that the response contains HTML content, allowing it to render the HTML accordingly.

The above is the detailed content of Why is My Go HTML Output Displayed as Plain Text?. 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
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!