can't assign requested address 错误解决

can't assign requested address 错误解决

转自:https://gocn.vip/article/314

最近一直在写新版本的beego2,在做MUX测试的时候遇到了这个问题,

BenchmarkBeegoMuxRequests-8         panic: Post http://127.0.0.1:59079/repos/: ... ests: dial tcp 127.0.0.1:59079: connect: can't assign requested address

这个错误看上去是我的测试耗掉了所有的local port,但是local port 不应该是复用的吗?

我的测试里面的代码片段是这样的:

for _, route := range routes {
    res, err := Request(route.method, ts.URL+route.path)
    if err != nil {
        panic(err)
    }
    res.Body.Close()
}

这个时候我去翻看了一下response里面的body的文档

// The default HTTP client's Transport does not
// attempt to reuse HTTP/1.0 or HTTP/1.1 TCP connections
// ("keep-alive") unless the Body is read to completion and is
// closed.

大家看到里面的话,只有当body读取并关闭,而我上面的代码只是关闭了,Body并没有读取。所以导致了client没有reuse TCP connection。

所以这个完全明白了,我们必须在关闭之前完全的读取Body里面的数据,我把原来的代码改成了下面之后就解决了问题

for _, route := range routes {
    res, err := Request(route.method, ts.URL+route.path)
    if err != nil {
        panic(err)
    }
    io.Copy(ioutil.Discard, res.Body)
    res.Body.Close()
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值