ctxhttp.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  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. // Package ctxhttp provides helper functions for performing context-aware HTTP requests.
  5. package ctxhttp // import "golang.org/x/net/context/ctxhttp"
  6. import (
  7. "io"
  8. "net/http"
  9. "net/url"
  10. "strings"
  11. "golang.org/x/net/context"
  12. )
  13. func nop() {}
  14. var (
  15. testHookContextDoneBeforeHeaders = nop
  16. testHookDoReturned = nop
  17. testHookDidBodyClose = nop
  18. )
  19. // Do sends an HTTP request with the provided http.Client and returns an HTTP response.
  20. // If the client is nil, http.DefaultClient is used.
  21. // If the context is canceled or times out, ctx.Err() will be returned.
  22. func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) {
  23. if client == nil {
  24. client = http.DefaultClient
  25. }
  26. // Request cancelation changed in Go 1.5, see cancelreq.go and cancelreq_go14.go.
  27. cancel := canceler(client, req)
  28. type responseAndError struct {
  29. resp *http.Response
  30. err error
  31. }
  32. result := make(chan responseAndError, 1)
  33. go func() {
  34. resp, err := client.Do(req)
  35. testHookDoReturned()
  36. result <- responseAndError{resp, err}
  37. }()
  38. var resp *http.Response
  39. select {
  40. case <-ctx.Done():
  41. testHookContextDoneBeforeHeaders()
  42. cancel()
  43. // Clean up after the goroutine calling client.Do:
  44. go func() {
  45. if r := <-result; r.resp != nil {
  46. testHookDidBodyClose()
  47. r.resp.Body.Close()
  48. }
  49. }()
  50. return nil, ctx.Err()
  51. case r := <-result:
  52. var err error
  53. resp, err = r.resp, r.err
  54. if err != nil {
  55. return resp, err
  56. }
  57. }
  58. c := make(chan struct{})
  59. go func() {
  60. select {
  61. case <-ctx.Done():
  62. cancel()
  63. case <-c:
  64. // The response's Body is closed.
  65. }
  66. }()
  67. resp.Body = &notifyingReader{resp.Body, c}
  68. return resp, nil
  69. }
  70. // Get issues a GET request via the Do function.
  71. func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error) {
  72. req, err := http.NewRequest("GET", url, nil)
  73. if err != nil {
  74. return nil, err
  75. }
  76. return Do(ctx, client, req)
  77. }
  78. // Head issues a HEAD request via the Do function.
  79. func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error) {
  80. req, err := http.NewRequest("HEAD", url, nil)
  81. if err != nil {
  82. return nil, err
  83. }
  84. return Do(ctx, client, req)
  85. }
  86. // Post issues a POST request via the Do function.
  87. func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error) {
  88. req, err := http.NewRequest("POST", url, body)
  89. if err != nil {
  90. return nil, err
  91. }
  92. req.Header.Set("Content-Type", bodyType)
  93. return Do(ctx, client, req)
  94. }
  95. // PostForm issues a POST request via the Do function.
  96. func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error) {
  97. return Post(ctx, client, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
  98. }
  99. // notifyingReader is an io.ReadCloser that closes the notify channel after
  100. // Close is called or a Read fails on the underlying ReadCloser.
  101. type notifyingReader struct {
  102. io.ReadCloser
  103. notify chan<- struct{}
  104. }
  105. func (r *notifyingReader) Read(p []byte) (int, error) {
  106. n, err := r.ReadCloser.Read(p)
  107. if err != nil && r.notify != nil {
  108. close(r.notify)
  109. r.notify = nil
  110. }
  111. return n, err
  112. }
  113. func (r *notifyingReader) Close() error {
  114. err := r.ReadCloser.Close()
  115. if r.notify != nil {
  116. close(r.notify)
  117. r.notify = nil
  118. }
  119. return err
  120. }