httputil.go 743 B

12345678910111213141516171819202122232425262728293031
  1. // Copyright 2015 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // borrowed from golang/net/context/ctxhttp/cancelreq.go
  5. // Package httputil provides HTTP utility functions.
  6. package httputil
  7. import (
  8. "io"
  9. "io/ioutil"
  10. "net/http"
  11. )
  12. func RequestCanceler(rt http.RoundTripper, req *http.Request) func() {
  13. ch := make(chan struct{})
  14. req.Cancel = ch
  15. return func() {
  16. close(ch)
  17. }
  18. }
  19. // GracefulClose drains http.Response.Body until it hits EOF
  20. // and closes it. This prevents TCP/TLS connections from closing,
  21. // therefore available for reuse.
  22. func GracefulClose(resp *http.Response) {
  23. io.Copy(ioutil.Discard, resp.Body)
  24. resp.Body.Close()
  25. }