ioutil.ReadAll导致goroutine泄漏

时间:2018-04-05 16:00:19

标签: go goroutine

为什么终止之前我有多个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

1 个答案:

答案 0 :(得分:7)

默认的http传输maintains a connection pool

  

DefaultTransport是Transport的默认实现,由DefaultClient使用。它根据需要建立网络连接,并将其缓存以供后续调用重用。

每个连接至少由一个goroutine管理。这不是泄漏,你只是不耐烦。如果你等待足够长的时间,你会看到连接最终关闭,goroutine消失了。默认空闲超时为90秒。

如果您想尽快关闭连接,请将http.Request.Closehttp.Transport.DisableKeepAlives设置为true。