更新代码
您好,我在 httpClient 中有内存泄漏,我添加了 sync.WaitGroup,现在我看到带有 httpClient 的 goroutine 没有关闭。如何解决?
func checkProxySOCKS(prox string, c chan QR, wg *sync.WaitGroup) (err error) {
defer wg.Done()
dialer, _ := proxy.SOCKS5("tcp", prox, nil, proxy.Direct)
timeout := time.Duration(2 * time.Second)
httpClient := &http.Client{
Timeout: timeout,
Transport: &http.Transport{
DisableKeepAlives: true,
Dial: dialer.Dial,
},
}
res, err := httpClient.Get("https://telegram.org/")
if err != nil {
c <- QR{Addr: prox, Res: false}
return
}
defer res.Body.Close()
io.Copy(ioutil.Discard, res.Body)
c <- QR{Addr: prox, Res: true}
return nil
} 我在这里创建 goroutines
for _, proxy := range splitedProxies {
wg.Add(1)
go checkProxySOCKS(proxy, respChan, &wg)
}
for range splitedProxies {
wg.Add(1)
r := <-respChan
if r.Res {
checkedProxiesArray = append(checkedProxiesArray, r.Addr)
}
wg.Done()
}
wg.Wait()
最佳答案
我已阅读评论,所以这应该可以解决您的问题
const (
timeout = time.Duration(1000 * time.Millisecond)
tt = time.Duration(100 * time.Millisecond)
)
func checkProxySOCKS(prox string, c chan QR, wg *sync.WaitGroup) (err error) {
defer wg.Done()
d := net.Dialer{
Timeout: tt,
KeepAlive: tt,
}
dialer, _ := proxy.SOCKS5("tcp", prox, nil, &d)
httpClient := &http.Client{
Timeout: timeout,
Transport: &http.Transport{
DisableKeepAlives: true,
Dial: dialer.Dial,
},
}
res, err := httpClient.Get("https://telegram.org/")
if err != nil {
c <- QR{Addr: prox, Res: false}
return
}
defer res.Body.Close()
io.Copy(ioutil.Discard, res.Body)
c <- QR{Addr: prox, Res: true}
return nil
}
关于http - Go httpClient 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50530245/