猿问

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

我不明白为什么代码正确生成 view.html 和 post.html 数据,但将其全部显示为原始文本。我一直在这里遵循指南,构建它时,我认为从 Execute 函数生成的 html 将发送到 ResponserWriter 来处理显示它,但我得到的错误似乎表明我对 Execute 的理解或者 ResponseWriter 是错误的。

查看.html


<h4>{{.Name}}</h4>


<font size="3">

    <div>{{printf "%s" .About}}</div>

</font>

<br>

<font size="2" align="right">

    <div align="right">{{.PostTime}}</div>

</font>

后.html


<form action="/post/" method="POST">


<div><textarea name="person" rows="1" cols="30">{{printf "%s" .Name}}</textarea></div>


<div><textarea name="body" rows="5" cols="100">{{printf "%s" .About}}</textarea></div>


<div><input type="submit" value="Submit"></div>


<a name="bottom"></a>

</form>

我目前一直在读取一个空的 dataf.txt 文件。


慕工程0101907
浏览 253回答 1
1回答

当年话下

正如所暗示的,这是因为您尚未设置内容类型。引自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.&nbsp; 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 文档。还有一条建议:在您的代码中,您虔诚地省略了检查返回的错误。不要那样做。您至少可以在控制台上打印它们。如果您不遗漏错误,您将为自己节省大量时间。
随时随地看视频慕课网APP

相关分类

Go
我要回答