duanshan1977 2018-06-01 06:37
浏览 890
已采纳

强制关闭Golang中的http连接

My program downloads a file from one server and then returns it to the user. Here is snippet of it:

// Make get request to target server
resp, httpErr := http.Get(url.String()) 

// Return error if http request is failed 
if httpErr != nil {
    fmt.Fprintln(w,"Http Request Failed :" ,httpErr.Error())
    return
}

//Setting up headers
w.Header().Set("Content-Disposition", "attachment; filename="+vid.Title+"."+format.Extension)
w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
w.Header().Set("Content-Length", strconv.Itoa(int(resp.ContentLength)))

// Copy instream of resp.Body to writer
io.Copy(w, resp.Body)

When the user stops the download or closes the connection I want to close the GET connection as well. But it does not get closed as I found via usage graph. How can I close the connection of the user?

  • 写回答

1条回答 默认 最新

  • doulangyu9636 2018-06-01 06:54
    关注

    You should close the Body of the request in any case:

    resp, httpErr := http.Get(url.String())
    if httpErr != nil {
       // handle error
       return
    }
    // if it's no error then defer the call for closing body
    defer resp.Body.Close()
    

    More should not be necessary to do. When the client closes the connection io.Copy returns with an error. io.Copy returns the number of bytes written and an error. You could check that, if you want to know if the copy succeded.

    written, err := io.Copy(w, resp.Body)
    if err != nil {
        // Copy did not succeed
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题