1 回答
TA贡献1890条经验 获得超9个赞
正如所暗示的,这是因为您尚未设置内容类型。引自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)
如果你自己没有设置内容类型,首先调用 toResponseWriter.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 文档。
还有一条建议:在您的代码中,您虔诚地省略了检查返回的错误。不要那样做。您至少可以在控制台上打印它们。如果您不遗漏错误,您将为自己节省大量时间。
- 1 回答
- 0 关注
- 252 浏览
添加回答
举报
