sig-kubernetes
sig-kubernetes copied to clipboard
[提问] client-go中的request函数会在请求结束的时候丢弃resp.Body,这是出于什么考虑呢?
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})
有什么作用。
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.
另外我找到了相关issue https://github.com/kubernetes/kubernetes/issues/30975
这是go http.Client的源码 https://github.com/golang/go/blob/master/src/net/http/client.go#L698