golang中强制关闭http连接

Man*_*eri 4 http go

我的程序从一台服务器下载一个文件,然后将其返回给用户。这是它的片段:

// 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)
Run Code Online (Sandbox Code Playgroud)

当用户停止下载或关闭连接时,我也想关闭 GET 连接。但正如我通过使用图发现的那样,它并没有关闭。如何关闭用户的连接?

mbu*_*ann 5

Body无论如何,您都应该关闭请求:

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()
Run Code Online (Sandbox Code Playgroud)

没有必要做更多的事情。当客户端关闭连接时,io.Copy会返回错误。io.Copy返回写入的字节数和错误。如果你想知道复制是否成功,你可以检查一下。

written, err := io.Copy(w, resp.Body)
if err != nil {
    // Copy did not succeed
}
Run Code Online (Sandbox Code Playgroud)