http - 关闭连接后写入响应错误

标签 http go

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

我唯一感兴趣的是respconn是如何关联的。我以为响应会将所有接收到的数据本身保存在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/

相关文章:

Golang Kafka 不消耗所有消息 offsetnewest

sencha touch 2 中的 HTTP 请求

c# - 在套接字监听器中检查请求是否通过 HTTP 或 HTTPS

java - 将 HTTP post 从 ruby​​ 转换为 java 或 groovy

java - HttpResponse 代码 302

go - 比较 nil 指针变量的值

go - 如何在生成交互式程序后捕获/记录所有内容

android - HttpConnection 中的 setAllowUserInteraction() 是什么

go - 如何使用 golang imap 获取 UID?

go - 在 Go 中解析多个模板