Last active
April 26, 2019 20:30
-
-
Save farhany/3bf4c0cc39cdc3ce3613d9e54ccdacae to your computer and use it in GitHub Desktop.
Close http client connections properly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Source: https://stackoverflow.com/questions/17948827/reusing-http-connections-in-golang | |
// It is the caller's responsibility to | |
// close Body. The default HTTP client's Transport may not | |
// reuse HTTP/1.x "keep-alive" TCP connections if the Body is | |
// not read to completion and closed. | |
package main | |
import ( | |
"fmt" | |
"io" | |
"io/ioutil" | |
"net/http" | |
"time" | |
) | |
func main() { | |
req, err := http.NewRequest(http.MethodGet, "https://github.com", nil) | |
if err != nil { | |
fmt.Println(err.Error()) | |
return | |
} | |
client := &http.Client{} | |
i := 0 | |
for { | |
resp, err := client.Do(req) | |
if err != nil { | |
fmt.Println(err.Error()) | |
return | |
} | |
_, _ = readBody(resp.Body) | |
fmt.Println("done ", i) | |
time.Sleep(5 * time.Second) | |
} | |
} | |
func readBody(readCloser io.ReadCloser) ([]byte, error) { | |
defer readCloser.Close() | |
body, err := ioutil.ReadAll(readCloser) | |
if err != nil { | |
return nil, err | |
} | |
return body, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment