gpt4 book ai didi

io - 使用 io.Copy 响应时,谁应该为错误负责?

转载 作者:IT王子 更新时间:2023-10-29 00:36:24 25 4
gpt4 key购买 nike

假设服务器需要向客户端响应一些数据,并且数据来自本地磁盘上的文件。然后我们写,

n, err := io.Copy(w, f)  // w is the ResponseWriter and f is the *os.File

我的想法是,io.Copy() 首先写入一个 header ,然后将数据从f 复制到w

err 不是 nil(例如 unexpected EOF)时,客户端仍然得到状态码 200,尽管响应正文包含一些内容错误的。

可能是本地磁盘坏了,也可能是客户端网络坏了。我们如何确定
err是服务端还是客户端导致的?

最佳答案

io.Copy 在目标 io.Writer 上调用 Writehttp.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)

所以是的,如果您的 HD 在执行Write 操作时出现故障,您已经编写了一个200 OK 响应,但是,如果您的响应指定了一个Content-Length 当您的响应长度不匹配时,客户端会知道有问题。

在 HTTP 1.1 和分 block 传输编码的情况下,理论上您可以在 HTTP 尾部响应之后指定失败 header 。遗憾的是,目前最常用的网络浏览器都不支持 HTTP 尾部。

来自@OneOfOne 的贡献:io.Copy 的错误不会指定哪一端失败;如果服务器或客户端。

So as a result, we can't point out the err should be logged as 4xx or 5xx, right?

如果您正在记录 HTTP 状态 header ,则记录您发送给客户端的内容作为响应;不应该是这样。

关于io - 使用 io.Copy 响应时,谁应该为错误负责?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26096944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com