duanmie9682 2017-09-06 18:30 采纳率: 100%
浏览 63

golang-似乎无法删除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"))
    }
}

I get measurements like this:

2.75
0.13
0.09
0.12
0.115

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)

What am I doing wrong?

  • 写回答

1条回答 默认 最新

  • douzai9405 2017-09-06 20:18
    关注

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

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决