英文:
HTML output is being interpreted as plain text instead of being received as html
问题
我确定这只是我在做一些愚蠢的事情,但我是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())
base.html的内容如下:
<!DOCTYPE html>
<html>
<body>
base.html
</body>
</html>
当我运行服务器并加载页面时,我看到模板中的HTML原样显示,而不是解释后的版本。原来,模板被包裹在pre标签中,并随后被包裹在一个新文档中。
那么是怎么回事呢?为什么Go默认将其视为纯文本而不是以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?
答案1
得分: 10
你需要添加一个带有Content-Type的头部。
w.Header().Set("Content-Type", "text/html")
英文:
You need to add a header with the Content-Type
w.Header().Set("Content-Type", "text/html")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论