为什么Go语言中的http.Request的主体是一个接口?

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

Why is the body of http.Request in go language an interface?

问题

我是一个Go语言初学者,我想知道为什么在Go语言中http.body是一个接口?
如果你能回答我,我将非常感谢你。

英文:

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。

答案1

得分: 1

我假设你希望看到[]byte而不是io.ReadCloser

io.Reader_和_io.Writer_允许数据进行_流式传输,因此可以在所有数据可用之前开始读取或写入。当请求过大无法放入可用内存时,这也能正常工作。

相比之下,字节切片需要在可以使用之前完整地获取所有内容。

英文:

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.

答案2

得分: 0

@Lars Christian Jensen的回答部分正确,但这并不是全部的真相。还有更多需要考虑的因素-例如,请查看http.Handler中的注释:

根据HTTP客户端软件、HTTP协议版本以及客户端和Go服务器之间的任何中间件,可能无法在写入ResponseWriter后从Request.Body中读取。谨慎的处理程序应该先读取Request.Body,然后再回复。

这意味着在构建http.Request结构体的body时,底层实现可能会因其他因素而有所不同。

另一个情况是处理测试-当我构造一个http.Request来测试处理程序函数时,body通常只是一个bytes.NewBuffer([]byte("{\"some\": \"json\"}"))

英文:

@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\"}"))

huangapple
  • 本文由 发表于 2021年10月1日 16:35:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/69402894.html
匿名

发表评论

匿名网友

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

确定