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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 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连接。
但是它并没有像我通过使用情况图所显示的那样关闭。如何关闭用户的连接?

在任何情况下,您都应关闭请求的正文:

1
2
3
4
5
6
7
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返回写入的字节数和错误。如果您想知道副本是否成功,可以检查一下。

1
2
3
4
written, err := io.Copy(w, resp.Body)
if err != nil {
    // Copy did not succeed
}