为什么终止之前我有多个goroutine,即使我关闭了resp.body
,而我只使用了阻止调用?如果我不消耗resp.Body
,它只会终止一个goroutine。
package main
import (
"fmt"
"io/ioutil"
"net/http"
"runtime"
"time"
)
func fetch() {
client := http.Client{Timeout: time.Second * 10}
url := "http://example.com"
req, err := http.NewRequest("POST", url, nil)
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
_, err = ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
}
func main() {
fmt.Println("#Goroutines:", runtime.NumGoroutine())
fetch()
// runtime.GC()
time.Sleep(time.Second * 5)
fmt.Println("#Goroutines:", runtime.NumGoroutine())
}
输出:
#Goroutines: 1
#Goroutines: 3
答案 0 :(得分:7)
默认的http传输maintains a connection pool。
DefaultTransport是Transport的默认实现,由DefaultClient使用。它根据需要建立网络连接,并将其缓存以供后续调用重用。
每个连接至少由一个goroutine管理。这不是泄漏,你只是不耐烦。如果你等待足够长的时间,你会看到连接最终关闭,goroutine消失了。默认空闲超时为90秒。
如果您想尽快关闭连接,请将http.Request.Close或http.Transport.DisableKeepAlives设置为true。