samad montazeri
samad montazeri

Reputation: 1273

Why is response body in golang is a readCloser?

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?

Upvotes: 2

Views: 1259

Answers (1)

Volker
Volker

Reputation: 42413

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.

Upvotes: 8

Related Questions