亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么以及何時 ResponseWriter 生成原始 html?

為什么以及何時 ResponseWriter 生成原始 html?

Go
慕工程0101907 2021-12-20 19:27:08
我不明白為什么代碼正確生成 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 文件。
查看完整描述

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 文檔。


還有一條建議:在您的代碼中,您虔誠地省略了檢查返回的錯誤。不要那樣做。您至少可以在控制臺上打印它們。如果您不遺漏錯誤,您將為自己節省大量時間。


查看完整回答
反對 回復 2021-12-20
  • 1 回答
  • 0 關注
  • 202 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號