Home > Software design >  Why is the body of http.Request in go language an interface?
Why is the body of http.Request in go language an interface?

Time:10-01

I am a go beginner,I want to know why http.body is an interface in go language? If you can answer me, I will thank you very much。

CodePudding user response:

I assume you expected to see []byte instead of io.ReadCloser.

io.Reader and io.Writer allows the data to be streamed, so it is possible to start reading or writing before all data is available. It will also work when the request is too large to fit in available memory.

For comparison; a byte slice would require the complete content to be available before it can be used.

CodePudding user response:

@Lars Christian Jensen's answer is partially correct, but that's not the entire truth. There are more considerations than this - for example take a look at the comment in http.Handler

Depending on the HTTP client software, HTTP protocol version, and any intermediaries between the client and the Go server, it may not be possible to read from the Request.Body after writing to the ResponseWriter. Cautious handlers should read the Request.Body first, and then reply.

This infers that the underlying implementation for a Body might differ depending on other factors while building the http.Request struct body.

Another case is handling tests - when I construct an http.Request to test a handler func, the body is usually just an bytes.NewBuffer([]byte("{\"some\": \"json\"}"))

  • Related