ctxhttp.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. // Do sends an HTTP request with the provided http.Client and returns an HTTP response.
  14. // If the client is nil, http.DefaultClient is used.
  15. // If the context is canceled or times out, ctx.Err() will be returned.
  16. func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) {
  17. if client == nil {
  18. client = http.DefaultClient
  19. }
  20. // Request cancelation changed in Go 1.5, see cancelreq.go and cancelreq_go14.go.
  21. cancel := canceler(client, req)
  22. type responseAndError struct {
  23. resp *http.Response
  24. err error
  25. }
  26. result := make(chan responseAndError, 1)
  27. go func() {
  28. resp, err := client.Do(req)
  29. result <- responseAndError{resp, err}
  30. }()
  31. select {
  32. case <-ctx.Done():
  33. cancel()
  34. return nil, ctx.Err()
  35. case r := <-result:
  36. return r.resp, r.err
  37. }
  38. }
  39. // Get issues a GET request via the Do function.
  40. func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error) {
  41. req, err := http.NewRequest("GET", url, nil)
  42. if err != nil {
  43. return nil, err
  44. }
  45. return Do(ctx, client, req)
  46. }
  47. // Head issues a HEAD request via the Do function.
  48. func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error) {
  49. req, err := http.NewRequest("HEAD", url, nil)
  50. if err != nil {
  51. return nil, err
  52. }
  53. return Do(ctx, client, req)
  54. }
  55. // Post issues a POST request via the Do function.
  56. func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error) {
  57. req, err := http.NewRequest("POST", url, body)
  58. if err != nil {
  59. return nil, err
  60. }
  61. req.Header.Set("Content-Type", bodyType)
  62. return Do(ctx, client, req)
  63. }
  64. // PostForm issues a POST request via the Do function.
  65. func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error) {
  66. return Post(ctx, client, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
  67. }