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()
}