http.Response.Write
关闭后,'use of closed network connection'
会从其中接收数据,从而导致net.Conn
错误。例如。我需要做这样的事情:
func Do(req *http.Request) *http.Response {
// ...
req.Write(conn)
var r = bufio.NewReader(conn)
var resp = http.ReadResponse(r, req)
conn.Close()
return resp
}
//...
var resp = Do(req)
resp.Write(anotherConn) // here is the error
但最后一行给出了以上错误。您可以说一个明显的解决方案是
http.Response
之后的conn.Close
,但我这样做的原因是resp.Write
必须将Do
写入它自己创建的req
中,然后仅返回conn
。我唯一感兴趣的是
resp
和conn
是如何关联的。我以为响应会将所有接收到的数据本身保存在req
中,然后不依赖于它从中接收到数据的连接。但这似乎不是这样。
最佳答案
ReadResponse
读取状态行和 header ,然后在Respons.Body
中公开响应主体,该主体直接访问基础连接以即时读取主体,而不是将整个主体(可能很多兆字节)加载到内存中。这允许实现尽可能高效,例如。流处理主体,而不是将其全部加载到内存中然后进行处理。
Per the docs:
The response body is streamed on demand as the Body field is read. If the network connection fails or the server terminates the response, Body.Read calls return an error.
关于http - 关闭连接后写入响应错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61120901/