所以发生了什么?为什么默认情况下将其视为纯文本而不是将其作为html发送,以便浏览器可以正确渲染它?当然,这肯定是一个简单的误解,但没有得到任何搜索。想法?

您需要添加一个包含Content-Type的标题

  w.Header()。Set(Content-Type,text / html)


I'm sure this is just something dumb I'm doing, but I'm new to Go, so not sure what's going on here. I have the following basic setup.

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 contents of base.html are as follows:

<DOCTYPE html>
<html>
    <body>
        base.html
    </body>
</html>

When I run the server and load the page, I see the HTML inside the template verbatim -- instead of the interpreted version. Turns out, the template is being wrapped in pre tags, and is subsequently being wrapped in a new document.

So what's going on? Why is go by default treating this as plain text rather than sending it over as html, so that the browser can render it properly? Surely this must be a simple misunderstanding, but not getting anything in searches. Ideas?

You need to add a header with the Content-Type

 w.Header().Set("Content-Type", "text/html")

这篇关于Golang的html输出被解释为纯文本,而不是被接收为html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!