为什么在Go语言中响应体是一个readCloser?

huangapple go评论81阅读模式
英文:

Why is response body in golang is a readCloser?

问题

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

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

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

主要问题是:http包是同时完整地读取header和body然后返回Response,还是只读取Header部分,当我们从Body读取时实际上是从一个连接中读取的?在完成整个body之前是否可能遇到错误(例如连接断开)?或者当我们获取响应时,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?

答案1

得分: 7

主要问题是:http包是否同时完整地读取头部和正文,然后返回响应?

不是的。

还是它只读取头部部分,当我们从正文中读取时,实际上是从连接中读取?

是的。

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

是的。

还是在我们收到响应时,正文已经完全接收并存储在内存中?

不是的。想象一下一个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.

huangapple
  • 本文由 发表于 2022年3月3日 21:28:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/71338019.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定