sig-kubernetes icon indicating copy to clipboard operation
sig-kubernetes copied to clipboard

[提问] client-go中的request函数会在请求结束的时候丢弃resp.Body,这是出于什么考虑呢?

Open gasxia opened this issue 4 years ago • 4 comments

https://github.com/kubernetes/client-go/blob/6c5935290e3335b200f75d874a19be3093e9c36b/rest/request.go#L785

			defer func() {
				const maxBodySlurpSize = 2 << 10
				if resp.ContentLength <= maxBodySlurpSize {
					io.Copy(ioutil.Discard, &io.LimitedReader{R: resp.Body, N: maxBodySlurpSize})
				}
				resp.Body.Close()
			}()

不明白 io.Copy(ioutil.Discard, &io.LimitedReader{R: resp.Body, N: maxBodySlurpSize}) 有什么作用。

gasxia avatar Aug 08 '20 15:08 gasxia

io.Copy(ioutil.Discard, &io.LimitedReader{R: resp.Body, N: maxBodySlurpSize}) 其实就是 body>dev/null 这段代码应该是参考了go的http.Client源码,如果body没有被读完且close,是不会复用底层TCP连接的

// The http Client and Transport guarantee that Body is always // non-nil, even on responses without a body or responses with // a zero-length body. It is the caller's responsibility to // close Body. The default HTTP client's Transport may not // reuse HTTP/1.x "keep-alive" TCP connections if the Body is // not read to completion and closed.

YouEclipse avatar Aug 08 '20 16:08 YouEclipse

另外我找到了相关issue https://github.com/kubernetes/kubernetes/issues/30975

YouEclipse avatar Aug 08 '20 16:08 YouEclipse

这是go http.Client的源码 https://github.com/golang/go/blob/master/src/net/http/client.go#L698

YouEclipse avatar Aug 08 '20 16:08 YouEclipse

谢谢 @YouEclipse

关于client-go中的request函数,我总结了一篇文章《学习 client-go 中 request 函数的实现》

gasxia avatar Aug 09 '20 12:08 gasxia