1 回答

TA貢獻(xiàn)1890條經(jīng)驗(yàn) 獲得超9個(gè)贊
正如所暗示的,這是因?yàn)槟形丛O(shè)置內(nèi)容類型。引自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)
如果你自己沒有設(shè)置內(nèi)容類型,首先調(diào)用 toResponseWriter.Write()會(huì)調(diào)用http.DetectContentType()猜測(cè)要設(shè)置的內(nèi)容。如果您發(fā)送的內(nèi)容以 開頭"<form>",則它不會(huì)被檢測(cè)為 HTML,但"text/plain; charset=utf-8"會(huì)被設(shè)置(“指示”瀏覽器將內(nèi)容顯示為文本,而不是嘗試將其解釋為 HTML)。
"<html>"例如,如果內(nèi)容以 開頭,則內(nèi)容類型"text/html; charset=utf-8"將自動(dòng)設(shè)置,無需進(jìn)一步操作即可工作。
但是,如果您知道要發(fā)送的內(nèi)容,請(qǐng)不要依賴自動(dòng)檢測(cè),而且自己設(shè)置它比在其上運(yùn)行檢測(cè)算法要快得多,因此只需在寫入/發(fā)送任何數(shù)據(jù)之前添加此行:
w.Header().Set("Content-Type", "text/html; charset=utf-8")
并使您的post.html模板成為完整、有效的 HTML 文檔。
還有一條建議:在您的代碼中,您虔誠(chéng)地省略了檢查返回的錯(cuò)誤。不要那樣做。您至少可以在控制臺(tái)上打印它們。如果您不遺漏錯(cuò)誤,您將為自己節(jié)省大量時(shí)間。
- 1 回答
- 0 關(guān)注
- 200 瀏覽
添加回答
舉報(bào)