最近一直在写新版本的 beego2,在做 MUX 测试的时候遇到了这个问题,
BenchmarkBeegoMuxRequests-8 panic: Post http://127.0.0.1:59079/repos/:owner/:repo/hooks/:id/tests: 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()
}