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:
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 With base.html containing the following:
base.html
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:
w.Header().Set("Content-Type", "text/html")
This header informs the browser that the response contains HTML content, allowing it to render the HTML accordingly.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3