golang-似乎无法删除http连接 [英] golang - can't seem to drop http connections
本文介绍了golang-似乎无法删除http连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试测量URL的连续加载时间,但是无法删除http连接并每次重新测量都重新开始.有了这段代码...
I'm trying to measure successive load times of a URL, but have been unable to drop an http connection and start fresh with each measurement. With this code...
func getloadtime (url string) float64 {
// setup client
tr := &http.Transport{
DisableKeepAlives: true}
client := &http.Client{Transport:tr}
// page load and measure
start := time.Now()
_, _ = client.Get(url)
return(time.Since(start).Seconds())
}
func main () {
for i := 0; i < 5; i++ {
fmt.Println(getloadtime("http://www.google.com"))
}
}
我得到这样的测量值:
2.75
0.13
0.09
0.12
0.115
因此,似乎从初始加载开始就维护了HTTP连接,因为后续加载要快得多.我也尝试将标题中的连接"设置为关闭",但得到的结果相同:
So it appears the http connection is being maintained from the initial load since the subsequent loads are much faster. I have also tried setting "Connection" to "Close" in the header, but get the same results:
req, err := http.NewRequest("GET", url, nil)
req.Header.Set("Connection", "close")
_, _ := client.Do(req)
我在做什么错了?
推荐答案
我认为您需要将GET的响应分配给变量,然后使用 response.Body.Close()
关闭连接>
I think you need to assign the response from the GET to a variable and then close the connection with response.Body.Close()
func getloadtime (url string) float64 {
// setup client
tr := &http.Transport{
DisableKeepAlives: true}
client := &http.Client{Transport:tr}
// page load and measure
start := time.Now()
response, _ := client.Get(url)
response.Body.Close()
return(time.Since(start).Seconds())
}
这篇关于golang-似乎无法删除http连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文