ctxhttp.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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. // Make local copies of test hooks closed over by goroutines below.
  34. // Prevents data races in tests.
  35. testHookDoReturned := testHookDoReturned
  36. testHookDidBodyClose := testHookDidBodyClose
  37. go func() {
  38. resp, err := client.Do(req)
  39. testHookDoReturned()
  40. result <- responseAndError{resp, err}
  41. }()
  42. var resp *http.Response
  43. select {
  44. case <-ctx.Done():
  45. testHookContextDoneBeforeHeaders()
  46. cancel()
  47. // Clean up after the goroutine calling client.Do:
  48. go func() {
  49. if r := <-result; r.resp != nil {
  50. testHookDidBodyClose()
  51. r.resp.Body.Close()
  52. }
  53. }()
  54. return nil, ctx.Err()
  55. case r := <-result:
  56. var err error
  57. resp, err = r.resp, r.err
  58. if err != nil {
  59. return resp, err
  60. }
  61. }
  62. c := make(chan struct{})
  63. go func() {
  64. select {
  65. case <-ctx.Done():
  66. cancel()
  67. case <-c:
  68. // The response's Body is closed.
  69. }
  70. }()
  71. resp.Body = &notifyingReader{resp.Body, c}
  72. return resp, nil
  73. }
  74. // Get issues a GET request via the Do function.
  75. func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error) {
  76. req, err := http.NewRequest("GET", url, nil)
  77. if err != nil {
  78. return nil, err
  79. }
  80. return Do(ctx, client, req)
  81. }
  82. // Head issues a HEAD request via the Do function.
  83. func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error) {
  84. req, err := http.NewRequest("HEAD", url, nil)
  85. if err != nil {
  86. return nil, err
  87. }
  88. return Do(ctx, client, req)
  89. }
  90. // Post issues a POST request via the Do function.
  91. func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error) {
  92. req, err := http.NewRequest("POST", url, body)
  93. if err != nil {
  94. return nil, err
  95. }
  96. req.Header.Set("Content-Type", bodyType)
  97. return Do(ctx, client, req)
  98. }
  99. // PostForm issues a POST request via the Do function.
  100. func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error) {
  101. return Post(ctx, client, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
  102. }
  103. // notifyingReader is an io.ReadCloser that closes the notify channel after
  104. // Close is called or a Read fails on the underlying ReadCloser.
  105. type notifyingReader struct {
  106. io.ReadCloser
  107. notify chan<- struct{}
  108. }
  109. func (r *notifyingReader) Read(p []byte) (int, error) {
  110. n, err := r.ReadCloser.Read(p)
  111. if err != nil && r.notify != nil {
  112. close(r.notify)
  113. r.notify = nil
  114. }
  115. return n, err
  116. }
  117. func (r *notifyingReader) Close() error {
  118. err := r.ReadCloser.Close()
  119. if r.notify != nil {
  120. close(r.notify)
  121. r.notify = nil
  122. }
  123. return err
  124. }