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

去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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器