Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcefully close http connection in golang

Tags:

http

go

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?

like image 850
Manish Champaneri Avatar asked Jun 01 '18 06:06

Manish Champaneri


1 Answers

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
}
like image 116
mbuechmann Avatar answered Nov 02 '22 22:11

mbuechmann