为什么golang中的响应体是readCloser?

发布于 2025-01-11 10:20:45 字数 390 浏览 0 评论 0原文

我想知道 golang 中的 http 包是如何工作的。我可以看到http响应的主体是这样的:

type Response struct {
    StatusCode int
    Header     Header
    Body       io.ReadCloser
}

Body是一个ReadCloser。这是为什么?

主要问题是:http包是否同时完整地读取 header 和 body,然后返回 Response 或它只读取 Header 部分,当我们读取时Body 我们实际上是从连接中读取内容吗?我们是否有可能在完成整个正文之前遇到错误(例如因为连接断开)?或者当我们收到响应时,正文已完全接收并驻留在内存中?

I'm wondering how http package in golang works. I can see that the body of http response is like this:

type Response struct {
    StatusCode int
    Header     Header
    Body       io.ReadCloser
}

The Body is a ReadCloser. Why is that?

The main question is: Does http package read header and body at the same time and completely and then returns the Response or it just reads the Header part and when we are reading from Body we are actually reading from a connection? Is it possible that we encounter an error before we finish the whole body(e.g because connection drops)? or the body is completely received and resides in the memory when we get the response?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

没企图 2025-01-18 10:20:45

正文是一个 ReadCloser。这是为什么?

因为您可以从中读取内容,并且完成后必须关闭它。

主要问题是:http包是否同时完整地读取header和body然后返回Response[?]

否。

或者它只是读取标题部分,而当我们从正文读取时,我们实际上是从连接读取?

是的

我们是否有可能在完成整个正文之前遇到错误(例如,因为连接断开)?

是的。

或者当我们收到响应时,正文已完全接收并驻留在内存中?

不。想想 4.5 TByte 的流。

The Body is a ReadCloser. Why is that?

Because you can Read from it and you have to Close it once you are done.

The main question is: Does http package read header and body at the same time and completely and then returns the Response [?]

No.

or it just reads the Header part and when we are reading from Body we are actually reading from a connection?

Yes

Is it possible that we encounter an error before we finish the whole body(e.g because connection drops)?

Yes.

or the body is completely received and resides in the memory when we get the response?

No. Think of a 4.5 TByte stream.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文