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 關注
- 202 瀏覽
添加回答
舉報