drp935159 2018-05-25 13:23
浏览 150
已采纳

去httpClient内存泄漏

UPDATED CODE

Hi I have memory leaks in httpClient, i've added sync.WaitGroup and now I see that goroutine with httpClient don't closed. How to fix it?

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

} Here i create 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()
  • 写回答

1条回答 默认 最新

  • dongpei2835 2018-05-27 20:17
    关注

    I'm read comments, so this should solve your problem

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。
  • ¥30 c#打开word开启修订并实时显示批注
  • ¥15 如何解决ldsc的这条报错/index error
  • ¥15 VS2022+WDK驱动开发环境
  • ¥30 关于#java#的问题,请各位专家解答!
  • ¥30 vue+element根据数据循环生成多个table,如何实现最后一列 平均分合并
  • ¥20 pcf8563时钟芯片不启振
  • ¥20 pip2.40更新pip2.43时报错
  • ¥15 换yum源但仍然用不了httpd
  • ¥50 C# 使用DEVMOD设置打印机首选项