栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

为什么以及何时ResponseWriter会生成原始html?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

为什么以及何时ResponseWriter会生成原始html?

如提示所示,这是因为您尚未设置内容类型。引用自

http.ResponseWriter

// Write writes the data to the connection as part of an HTTP reply.// If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK)// before writing the data.  If the Header does not contain a// Content-Type line, Write adds a Content-Type set to the result of passing// the initial 512 bytes of written data to DetectContentType.Write([]byte) (int, error)

如果您自己未设置内容类型,则第一个调用

ResponseWriter.Write()
将调用
http.DetectContentType()
以猜测要设置的内容。如果您发送的内容以开头
"<form>"
,则不会将其检测为HTML,而是
"text/plain;charset=utf-8"
会进行设置(“指示”浏览器将内容显示为文本,而不尝试将其解释为HTML)。

"<html>"
例如,如果内容以开头,则内容类型
"text/html; charset=utf-8"
将自动设置,并且无需进一步操作即可工作。

但是,如果您知道要发送的内容,请不要依赖自动检测,而且,自己设置它比在其上运行检测算法要快得多,因此只需在写入/发送任何数据之前添加以下行即可:

w.Header().Set("Content-Type", "text/html; charset=utf-8")

并使

post.html
模板成为完整的有效HTML文档。

Also another piece of advice: in your pre you religiously omit checking
returned errors. Don’t do that. The least you could do is print them on the
console. You will save a lot of time for yourself if you don’t omit errors.



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/448111.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号