[英]Forcefully close http connection in golang
我的程序從一個服務器下載文件,然后將其返回給用戶。 這是它的片段:
// 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)
當用戶停止下載或關閉連接時,我也想關閉GET連接。 但是我沒有通過使用圖找到它。 如何關閉用戶的連接?
您應該在任何情況下關閉請求的正文:
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()
不應該做更多的事情。 當客戶端關閉連接時, io.Copy
返回錯誤。 io.Copy
返回寫入的字節數和錯誤。 如果你想知道副本是否成功,你可以檢查一下。
written, err := io.Copy(w, resp.Body)
if err != nil {
// Copy did not succeed
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.