gpt4 book ai didi

http - Go httpClient 内存泄漏

转载 作者:数据小太阳 更新时间:2023-10-29 03:42:08 25 4
gpt4 key购买 nike

更新代码

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com