io.Copy
对目标io.Writer
调用Write
。 http.ResponseWriter
的对Write
方法文档指定此行为:
// 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)
这意味着它会先调用WriteHeader
:
// WriteHeader sends an HTTP response header with status code.
// If WriteHeader is not called explicitly, the first call to Write
// will trigger an implicit WriteHeader(http.StatusOK).
// Thus explicit calls to WriteHeader are mainly used to
// send error codes.
WriteHeader(int)
所以,是的,如果你的硬盘是Write
操作过程中失败的somewhen你“ d已经写了一个200 OK
响应,但是,如果您的响应指定了Content-Length
,那么当您的响应长度不匹配时,客户端就会知道有问题。
对于HTTP 1.1和分块传输编码,理论上可以在HTTP预告片中的响应之后指定失败标头。遗憾的是,当前最常用的Web浏览器不支持HTTP预告片。
@OneOfOne的贡献:io.Copy
的错误不会指定哪一端失败;如果服务器或客户端。
因此,我们不能指出err应该被记录为4xx或5xx,对吧?
如果您正在记录HTTP状态标题,然后记录您发送客户端作为响应;不是它应该的。
您还应该考虑使用'http.ServeFile'来返回内容。如果你出于某种原因不能,或者如果它奇迹般地超过了你的需要,那么就如何实施它。您可以看到它如何处理错误问题并将该处理复制到您的代码中 - 假设您不能自己使用“ServeFile”。 – 2014-09-30 02:07:14