更新代码
嗨我在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()
答案 0 :(得分:0)
我读了评论,所以这应该可以解决你的问题
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
}