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())
With base.html containing the following:
<code class="html"><DOCTYPE html> <html> <body> base.html </body> </html></code>
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>
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!