http - Go httpClient 内存泄漏

标签 http go memory-leaks

更新代码

您好,我在 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/

相关文章:

http - 跳过 Jackrabbit 登录提示

rest - 同时使用 HTTP 和 WebSockets 时的 API 命名约定

http - katalon automation recorder可以用来操作http post参数吗

javascript - 如何在 Ajax 请求后释放内存

http - curl 停止协商 SPNEGO - mech unknown 的 unknown mech-code 0

go - 如何遍历特定文件夹

arrays - 在golang中转储接口(interface)数组

go - 如何使用 golang knq/chromedp 检查页面中是否存在元素

C++ - 删除包含 vector 的结构 vector 会导致内存泄漏吗?

ios - 如何修复 IOS 中 SBJSON 文件中的内存泄漏