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> <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>
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!