Why is response body in golang is a readCloser?

Issue

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?

Solution

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.

Answered By – Volker

Answer Checked By – Katrina (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.